How to read CSV files in Python using csv.reader()
Published on Aug. 22, 2023, 12:18 p.m.
To read CSV files in Python using csv.reader()
, you can use the following code:
import csv
with open('file.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
This code opens the CSV file in read mode using the open()
function, and then creates a csv.reader()
object by passing the file object to it. It then iterates over the rows in the CSV file using a for
loop, and prints each row to the console.
You can also specify different delimiters and quote characters using the delimiter
and quotechar
arguments. For example, to use tabs as the delimiter and double quotes as the quote character, you can modify the code like this:
import csv
with open('file.csv', 'r') as file:
reader = csv.reader(file, delimiter='\t', quotechar='"')
for row in reader:
print(row)
This code creates a csv.reader()
object with the delimiter
argument set to '\t'
(tab) and quotechar
argument set to '"'
(double quotes), which tells Python to use those characters as the delimiter and quote characters instead of the default ,
and "
. The rest of the code is the same.