与txt文件相比,CSV(Comma Separated Value)文件可以把数据组织的更有层次。而且CSV文件可以被Excel读取编辑,所以它能很方便的在不同应用之间传递数据。
下面给出处理CSV文件的一些关键代码:
import csv
infile = open(filename) # For reading. Also infile = open(filename,'r')
infile.close() # An open file locks other applications out
rows = csv.reader(infile) # Read row
f = open(filename, 'w', newline='') # Open for writing
csv.writer(f).writerows(rowlist) # Write all rows at once
csv.writer(f).writerow(row) # Write one row
f.close()
读取CSV文件并把内容添加到一个列表(list)中:
import csv
def read_csv_file1(filename):
"""Reads a CSV file and print it as a list of rows."""
f = open(filename)
data = []
for row in csv.reader(f):
data.append(row)
print(data)
f.close()
将列表写入CSV文件:
def write_csv(filename):
import csv
L = [['Date', 'Name', 'Notes'],
['2016/1/18', 'Martin Luther King Day', 'Federal Holiday'],
['2016/2/2','Groundhog Day', 'Observance'],
['2016/2/8','Chinese New Year', 'Observance'],
['2016/2/14','Valentine\'s Day', 'Obervance'],
['2016/5/8','Mother\'s Day', 'Observance'],
['2016/8/19','Statehood Day', 'Hawaii Holiday'],
['2016/10/28','Nevada Day', 'Nevada Holiday']]
f = open(filename, 'w', newline='')
for item in L:
csv.writer(f).writerow(item)
f.close()
这里open函数中使用newline=' '是为了避免在不同行之间生成多余的空行。自己试验一下就知道了。