您可以使用 DictReader 和 DictWriter 保存为带有标题的新文件...
file_read = csv.DictReader(open('/tmp/test.csv', 'rb'),
['name','street','area'], delimiter=';')
file_write = csv.DictWriter(open('/tmp/test-headers.csv', 'wb'),
['name','street','area'], delimiter=';')
file_write.writeheader()
file_write.writerows(file_read)
或者,如果您只想在脚本中使用该文件:
file_read = csv.DictReader(open('/tmp/test.csv', 'rb'),
['name','street','area'], delimiter=';')
for row in file_read:
print row
以上打印:
{'street': ' 1st street', 'name': 'jack', 'area': ' New York'}
{'street': ' 2nd street', 'name': 'sally', 'area': ' New York'}