how to read a CSV file line by line with or without header in python

#Read a CSV file line by line using csv.reader

#Suppose we have a csv file students.csv and its contents are,
Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning
32,Shaun,Java,Tokyo,Morning

#With csv module’s reader class object we can iterate over the lines of a csv file as a list of values, where each value in the list is a cell value. Let’s understand with an example,

from csv import reader
# open file in read mode
with open('students.csv', 'r') as read_obj:
    # pass the file object to reader() to get the reader object
    csv_reader = reader(read_obj)
    # Iterate over each row in the csv using reader object
    for row in csv_reader:
        # row variable is a list that represents a row in csv
        print(row)

Output:
['Id', 'Name', 'Course', 'City', 'Session']
['21', 'Mark', 'Python', 'London', 'Morning']
['22', 'John', 'Python', 'Tokyo', 'Evening']
['23', 'Sam', 'Python', 'Paris', 'Morning']
['32', 'Shaun', 'Java', 'Tokyo', 'Morning']

3.67
9
Patr2016 95 points

                                    #Read a CSV file line by line using csv module DictReader object

#Suppose we have a csv file students.csv and its contents are,
Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning
32,Shaun,Java,Tokyo,Morning

#With csv module’s DictReader class object we can iterate over the lines of a csv file as a dictionary i.e.
#for each row a dictionary is returned, which contains the pair of column names and cell values for that row.
#Let’s understand with an example,

from csv import DictReader
# open file in read mode
with open('students.csv', 'r') as read_obj:
    # pass the file object to DictReader() to get the DictReader object
    csv_dict_reader = DictReader(read_obj)
    # iterate over each line as a ordered dictionary
    for row in csv_dict_reader:
        # row variable is a dictionary that represents a row in csv
        print(row)

Output:
{'Id': '21', 'Name': 'Mark', 'Course': 'Python', 'City': 'London', 'Session': 'Morning'}
{'Id': '22', 'Name': 'John', 'Course': 'Python', 'City': 'Tokyo', 'Session': 'Evening'}
{'Id': '23', 'Name': 'Sam', 'Course': 'Python', 'City': 'Paris', 'Session': 'Morning'}
{'Id': '32', 'Name': 'Shaun', 'Course': 'Java', 'City': 'Tokyo', 'Session': 'Morning'}

3.67 (9 Votes)
0
3
1
SGoins 90 points

                                    #Get column names from header in csv file

#Suppose we have a csv file students.csv and its contents are,
Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning
32,Shaun,Java,Tokyo,Morning

#DictReader class has a member function that returns the column names of the csv file as list.
#let’s see how to use it,

from csv import DictReader
# open file in read mode
with open('students.csv', 'r') as read_obj:
    # pass the file object to DictReader() to get the DictReader object
    csv_dict_reader = DictReader(read_obj)
    # get column names from a csv file
    column_names = csv_dict_reader.fieldnames
    print(column_names)

Output:
['Id', 'Name', 'Course', 'City', 'Session']

3 (1 Votes)
0
0
0
Buzzy613 105 points

                                    #Read a CSV file without header

#Suppose we have a csv file students.csv and its contents are,
Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning
32,Shaun,Java,Tokyo,Morning

#In the previous example we iterated through all the rows of csv file including header. But suppose we want to skip the header and iterate over the remaining rows of csv file.
#Let’s see how to do that,

from csv import reader
# skip first line i.e. read header first and then iterate over each row od csv as a list
with open('students.csv', 'r') as read_obj:
    csv_reader = reader(read_obj)
    header = next(csv_reader)
    # Check file as empty
    if header != None:
        # Iterate over each row after the header in the csv
        for row in csv_reader:
            # row variable is a list that represents a row in csv
            print(row)

Output:
['21', 'Mark', 'Python', 'London', 'Morning']
['22', 'John', 'Python', 'Tokyo', 'Evening']
['23', 'Sam', 'Python', 'Paris', 'Morning']
['32', 'Shaun', 'Java', 'Tokyo', 'Morning']
Header was: 
['Id', 'Name', 'Course', 'City', 'Session']

0
0
3.67
6
Talmage 105 points

                                    #Read specific columns from a csv file while iterating line by line

#Suppose we have a csv file students.csv and its contents are,
Id,Name,Course,City,Session
21,Mark,Python,London,Morning
22,John,Python,Tokyo,Evening
23,Sam,Python,Paris,Morning
32,Shaun,Java,Tokyo,Morning


#Read specific columns (by column name) in a csv file while iterating row by row


#Iterate over all the rows of students.csv file line by line, but print only two columns of for each row,

from csv import DictReader
# iterate over each line as a ordered dictionary and print only few column by column name
with open('students.csv', 'r') as read_obj:
    csv_dict_reader = DictReader(read_obj)
    for row in csv_dict_reader:
        print(row['Id'], row['Name'])

Output:
21 Mark
22 John
23 Sam
32 Shaun


#Read specific columns (by column Number) in a csv file while iterating row by row


#Iterate over all rows students.csv and for each row print contents of 2ns and 3rd column,

from csv import reader
# iterate over each line as a ordered dictionary and print only few column by column Number
with open('students.csv', 'r') as read_obj:
    csv_reader = reader(read_obj)
    for row in csv_reader:
        print(row[1], row[2])

Output:
Name Course
Mark Python
John Python
Sam Python
Shaun Java

3.67 (6 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source