深度阅读

How to read CSV files in Python using csv.reader()

作者
作者
2023年08月22日
更新时间
11.58 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。