Python Read CSV File

Read CSV File in Python

You can read a CSV file in Python and access the values inside the csv file at element level.

In this tutorial, we will go through some of the following ways to read a CSV file and access the elements of this CSV file.

  • Read CSV file using Python csv library.
  • Read CSV file using Python pandas library.
  • Read CSV file using for loop and string split operation.

Input CSV File

We shall consider the following input csv file, in the following ongoing examples to read CSV file in Python.

a,b,c
32,56,84
41,98,73
21,46,72
Copy

Read CSV File using Python csv package

In this example, we will use csv package to read the rows of the csv file.

  • csv.reader(csvfile) returns an iterator to loop over lines of csvfile.
  • csvreader.__next__() returns next row of the reader’s iterable object. We use this to read the field names, which are assumed to be present as first row.
  • Then we use for loop to iterate over csvreader iterable object to read the remaining rows.

Python Program

import csv

with open('data.csv','r') as csvfile:
	#reader can iterate over lines of csv file
	csvreader = csv.reader(csvfile)
	
	#reading first row of field names
	fields = csvreader.__next__()
	print('Field Names\n--------------')
	for field in fields:
		print("%8s"%field, end='')

	print('\nRows\n---------------------')	
	#reading rows
	for row in csvreader:
		#access and print each field value of row
		for col in row: 
			print("%8s"%col, end='')
		print('\n')
Copy

Output

Field Names
--------------
       a       b       c
Rows
---------------------
      32      56      84

      41      98      73

      21      46      72

Read CSV file using Python pandas library

If you can use pandas library, this is the most easiest way to read a CSV file in Python. pandas.read_csv(csv_file_name) reads the CSV file csv_file_name, and returns a DataFrame. You can access column names and data rows from this dataframe.

Python Program

import pandas as pd
	
# Load dataframe from csv
df = pd.read_csv("data.csv")

# Print dataframe
print(df)
Copy

Output

    a   b   c
0  32  56  84
1  41  98  73
2  21  46  72

Read CSV File using For Loop and String Split Operation

In this example, we will use Python For Loop and Split String Operation to read csv file.

We shall read the file, and for each line, we shall split the string by separator of fields.

Python Program

with open('data.csv') as fp:
	#field names
	print('Field Names\n--------------')
	fields = fp.readline()
	for field in fields.split(','):
		print("%8s"%field, end='')
	
	print('Rows\n---------------------')	
	#reading data rows
	for line in fp:
		chunks = line.split(',')
		for chunk in chunks:
			print("%8s"%chunk, end='')
Copy

Output

Field Names
--------------
       a       b      c
Rows
---------------------
      32      56     84
      41      98     73
      21      46      72

Summary

In this tutorial of Python Examples, we learned how to read a CSV file in Python and access each of the elements in it, through different ways, using well detailed example programs.

Related Tutorials

Code copied to clipboard successfully 👍