Load & Import CSV File Row by Row in Python (Example Code)

In this Python tutorial you’ll learn how to read a pandas DataFrame in a CSV file line by line.

Setting up the Example

import pandas as pd                           # Import pandas library in Python
my_df = pd.DataFrame({'A':range(100, 105),    # Construct new pandas DataFrame
                      'B':[9, 3, 7, 1, 2],
                      'C':['a', 'f', 'c', 'f', 'f'],
                      'D':range(35, 30, - 1)})
print(my_df)
#      A  B  C   D
# 0  100  9  a  35
# 1  101  3  f  34
# 2  102  7  c  33
# 3  103  1  f  32
# 4  104  2  f  31
my_df.to_csv('my_df.csv')                     # Write exemplifying DataFrame to folder

Example: Read CSV File Row by Row

import csv                                    # Import csv library
with open('my_df.csv', 'r') as f:             # Importing each row by its own
    reader = csv.reader(f, delimiter='t')
    for index, row in enumerate(reader):
        print('Row No.', index, 'contains the following values:', row)
# Row No. 0 contains the following values: [',A,B,C,D']
# Row No. 1 contains the following values: ['0,100,9,a,35']
# Row No. 2 contains the following values: ['1,101,3,f,34']
# Row No. 3 contains the following values: ['2,102,7,c,33']
# Row No. 4 contains the following values: ['3,103,1,f,32']
# Row No. 5 contains the following values: ['4,104,2,f,31']

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top