使用encoding/csv包提供的函数进行CSV文件的读写操作
encoding/csv
encoding/csv
import csv
csv.readercsv.reader
data.csv
Name,Age,City John,25,New York Lisa,30,San Francisco David,40,Los Angeles
csv.reader
with open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)
输出结果:
['Name', 'Age', 'City'] ['John', '25', 'New York'] ['Lisa', '30', 'San Francisco'] ['David', '40', 'Los Angeles']
可以看到,每一行的数据以列表的形式返回。其中,第一行是CSV文件的表头,接下来是数据行。
csv.readercsv.writer
data.csvcsv.writer
data = [ ['Name', 'Age', 'City'], ['John', '25', 'New York'], ['Lisa', '30', 'San Francisco'], ['David', '40', 'Los Angeles'] ] with open('data.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerows(data)
newline=''
data.csv
encoding/csvcsv.DictReadercsv.DictWriter
encoding/csvencoding/csvencoding/csv