Reading rows from a CSV file in Python

read csv file in python pandas
python read csv line by line
how to read a specific line from a csv file in python
python read csv example
python csv read specific row
python read csv into list
how to read csv file in python without pandas
python read csv into variables

I have a CSV file, here is a sample of what it looks like:

Year:  Dec: Jan:
1      50   60
2      25   50
3      30   30
4      40   20
5      10   10

I know how to read the file in and print each column (for ex. - ['Year', '1', '2', '3', etc]). But what I actually want to do is read the rows, which would be like this ['Year', 'Dec', 'Jan'] and then ['1', '50', '60'] and so on.

And then I would like to store those numbers ['1', '50', '60'] into variables so I can total them later for ex.:

Year_1 = ['50', '60']. Then I can do sum(Year_1) = 110.

How would I go about doing that in Python 3?

You could do something like this:

with open("data1.txt") as f:
    lis = [line.split() for line in f]        # create a list of lists
    for i, x in enumerate(lis):              #print the list items 
        print "line{0} = {1}".format(i, x)

# output 
line0 = ['Year:', 'Dec:', 'Jan:']
line1 = ['1', '50', '60']
line2 = ['2', '25', '50']
line3 = ['3', '30', '30']
line4 = ['4', '40', '20']
line5 = ['5', '10', '10']

or :

with open("data1.txt") as f:
    for i, line in enumerate(f):             
        print "line {0} = {1}".format(i, line.split())

# output         
line 0 = ['Year:', 'Dec:', 'Jan:']
line 1 = ['1', '50', '60']
line 2 = ['2', '25', '50']
line 3 = ['3', '30', '30']
line 4 = ['4', '40', '20']
line 5 = ['5', '10', '10']

Edit:

with open('data1.txt') as f:
    print "{0}".format(f.readline().split())
    for x in f:
        x = x.split()
        print "{0} = {1}".format(x[0],sum(map(int, x[1:])))

# output          
['Year:', 'Dec:', 'Jan:']
1 = 110
2 = 75
3 = 60
4 = 60
5 = 20

Reading CSV files in Python, import csv with open('example.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter Duration: 9:24 Posted: 29 Jul 2014 USing csv.reader (): At first, the CSV file is opened using the open () method in ‘r’ mode (specifies read mode while opening a file) which returns the file object then it is read by using the reader () method of CSV module that returns the reader object that iterates throughout the lines in the specified CSV document.

Use the csv module:

import csv

with open("test.csv", "r") as f:
    reader = csv.reader(f, delimiter="\t")
    for i, line in enumerate(reader):
        print 'line[{}] = {}'.format(i, line)

Output:

line[0] = ['Year:', 'Dec:', 'Jan:']
line[1] = ['1', '50', '60']
line[2] = ['2', '25', '50']
line[3] = ['3', '30', '30']
line[4] = ['4', '40', '20']
line[5] = ['5', '10', '10']

Python: Read a CSV file line by line with or without header , How did it work ? Open the file 'students. csv' in read mode and create a file object. Create a reader object (iterator) by passing file object in csv. reader() function. Now once we have this reader object, which is an iterator, then use this iterator with for loop to read individual rows of the csv as list of values. Reading a CSV File The read_csv function of the pandas library is used read the content of a CSV file into the python environment as a pandas DataFrame. The function can read the files from the OS by using proper path to the file. import pandas as pd data = pd.read_csv('path/input.csv') print (data)

Reading it columnwise is harder?

Anyway this reads the line and stores the values in a list:

for line in open("csvfile.csv"):
    csv_row = line.split() #returns a list ["1","50","60"]

Modern solution:

# pip install pandas
import pandas as pd 
df = pd.read_table("csvfile.csv", sep=" ")

csv — CSV File Reading and Writing — Python 3.8.5 documentation, Looping through rows; Extracting information from a CSV file; Creating lists; Converting lists to sets; Eventually, outputting� Read a CSV file line by line using csv.reader. Open the file ‘students.csv’ in read mode and create a file object. Create a reader object (iterator) by passing file object in csv.reader() function. Now once we have this reader object, which is an iterator, then use this iterator with for loop to

import csv

with open('filepath/filename.csv', "rt", encoding='ascii') as infile:
    read = csv.reader(infile)
    for row in read :
        print (row)

This will solve your problem. Don't forget to give the encoding.

Python for Beginners: Reading & Manipulating CSV Files, Learn how to read, process, and parse CSV from text files using Python. column 1 name,column 2 name, column 3 name first row data 1,first row data 2, first� Read specific columns from a CSV file in Python. Pandas consist of read_csv function which is used to read the required CSV file and usecols is used to get the required columns. We have to make sure that python is searching for the file in the directory it is present. In order to that, we need to import a module called os. This module provides

#  This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)

# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`

for row in reader:
    if rownum == 0:
        header = row  #work with header row if you like
    else:
    colnum = 0
    for col in row:
        if colnum == 0:
            year = float(col)
        if colnum == 1:
            dec = float(col)
        if colnum == 2:
            jan = float(col)
        colnum += 1
    # end of if structure

# now we can process results
if rownum != 0:
    print(year, dec, jan)
    total_years = total_years + year
    print(total_years)

# time to go after the next row/bar
rownum += 1

ifile.close()

A bit late but nonetheless... You need to create and identify the csv file named "years.csv":

Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10

Reading and Writing CSV Files in Python – Real Python, In this video, you'll learn how to read standard CSV files using Python's built in csv DictReader(csv_file, delimiter=',') line_count = 0 for row in csv_reader:� csvReader = csv.reader (csvDataFile) for row in csvReader: dates.append (row [0]) scores.append (row [1]) return dates, scores. dates,scores = readMyFile ('file.csv') print (dates) print (scores) Given a filename, the function will read and parse the csv data.

Reading CSVs With Python's "csv" Module – Real Python, In this tutorial, we will learn to read CSV files with different formats in Python with 'r') as file: reader = csv.reader(file, delimiter = '\t') for row in reader: print(row). Reading the CSV into a pandas DataFrame is quick and straightforward: import pandas df = pandas.read_csv('hrdata.csv') print(df) That’s it: three lines of code, and only one of them is doing the actual work. pandas.read_csv () opens, analyzes, and reads the CSV file provided, and stores the data in a DataFrame.

Reading CSV files in Python, The standard format is defined by rows and columns data. Moreover, each row is terminated by a newline to begin the next row. Also within the� import pandas as pd data = pd.read_csv("names.csv", nrows=1) You can mention the number of lines to be read in the nrows parameter.

Reading and Writing CSV Files in Python using CSV Module , Reading into a list. Here is an example script to read a CSV file into a list. Each row will become its own list and then can be referenced by the� Steps to Select Rows from Pandas DataFrame Step 1: Data Setup Pandas read_csv () is an inbuilt function that is used to import the data from a CSV file and analyze that data in Python. So, we will import the Dataset from the CSV file, and it will be automatically converted to Pandas DataFrame and then select the Data from DataFrame.

Comments
  • See the comment I left for @Joel Cornett's answer
  • @Goose you can do lis[0] to get line 0, see my edited answer.
  • Ok got it, now how can I find the element in lis[0]? For example, I need to total the month numbers (50+60) so for year 1 it would be 110. lis[0][0] doesn't work for me. That was my main goal.
  • @Goose see my edited answer, You didn't mentioned this at all in the original question.
  • Sorry I thought once I could read the columns I could figure it out myself. But your edited method isnt working for my "actual" file for some reason. See: i.imgur.com/EORK2.png. What I was trying to do is store each of the totals in a variable. so year1 = 110, etc. I'm not trying to just print it out, sorry for being so vague. I thought it would've been easier to do when I posted the question.
  • How would I make it so it prints the lines separately and not all together (ex. line 0 = ['Year:', 'Dec:', 'Jan:']), I tried print (line[0]) but it didn't work.
  • I was getting the following error in python3: iterator should return strings, not bytes (did you open the file in text mode?) and solved it by changing rb to rt.
  • @J0ANMM Good callout. This answer was written at a time when Python 3 did not have as wide adoption and was thus implicitly targeted to Python 2. I will update the answer accordingly.
  • When I implement this into my program I get an error: 'list' object has no attribute 'split'
  • Works like a charm here on 2.7 and 3.3
  • Perhaps its my file, the text above is just a sample, the real file is much bigger.
  • Size hasn't got anything to do with it. It is with your program, which we would need to see to help you further :)
  • And what if a value in the line contains the split character?
  • seems incorrect access mode. it should be r+ , not rt
  • You forgot to indent the code block after else. But nice solution.