CSV 表示Comma-Separated Values(逗号分隔的值),是简化的电子表格,实质为纯文本文件。
CSV 文件是简单的,缺少 Excel 电子表格的许多功能。例如,CSV 文件中:
• 值没有类型,所有东西都是字符串;
• 没有字体大小或颜色的设置;
• 没有多个工作表;
• 不能指定单元格的宽度和高度;
• 不能合并单元格;
• 不能嵌入图像或图表等等
CSV
csv.reader读取
我们现在有一个CSV文件,它看起来是这丫:
1 2 3 4 5 6 7
| 4/5/2015 13:34,Apples,73 4/5/2015 3:41,Cherries,85 4/6/2015 12:46,Pears,14 4/8/2015 8:59,Oranges,52 4/10/2015 2:07,Apples,152 4/10/2015 18:10,Bananas,23 4/10/2015 2:40,Strawberries,98
|
我们用python自带的 csv 模块从 CSV 文件中读取数据,并创建一个 Reader 对象。
1 2 3 4 5 6
| import csv exampleFile = open('example.csv') exampleReader = csv.reader(exampleFile)
for row in exampleReader: print('Row #' + str(exampleReader.line_num) + ' ' + str(row))
|
1 2 3 4 5 6 7
| Row Row Row Row Row Row Row
|
Reader 对象实质是返回一个列表,
1 2 3 4 5 6 7 8 9 10 11 12 13
| import csv
filename = 'example.csv'
try: with open(filename) as f: exampleReader = csv.reader(f) exampleData = list(exampleReader) except FileNotFoundError: print('无法打开文件:', filename) else: for item in exampleData: print('%-20s%-15s%-5s' % (item[0], item[1], item[2]))
|
1 2 3 4 5 6 7
| 4/5/2014 13:34 Apples 73 4/5/2014 3:41 Cherries 85 4/6/2014 12:46 Pears 14 4/8/2014 8:59 Oranges 52 4/10/2014 2:07 Apples 152 4/10/2014 18:10 Bananas 23 4/10/2014 2:40 Strawberries 98
|
1 2 3 4 5 6
| exampleData[0]
exampleData[1][1]
exampleData[6][1]
|
csv.writer写入
Writer 对象让你将数据写入 CSV 文件。要创建一个 Writer对象,就使用csv.writer()函数。
1 2 3 4 5 6 7 8 9 10 11
| import csv outputFile = open('output.csv', 'w', newline='')
outputWriter = csv.writer(outputFile, delimiter='\t', lineterminator='\n\n) outputWriter.writerow(['spam', 'eggs', 'bacon', 'ham']) # 21 outputWriter.writerow(['Hello, world!', 'eggs', 'bacon', 'ham']) # 32 outputWriter.writerow([1, 2, 3.141592, 4]) # 16 outputFile.close()
|
在 Windows 上,需要为 open()函数的 newline 关键字参数传入一个空字符串防止多余的换行。
如果需输入中文、阿拉伯文等,需传入encoding 参数,比如:
open('output.csv', 'w', newline='',encoding = 'utf-8-sig')
从 CSV 文件中删除表头
我们来写个可以批量删除几百 个CSV文件的第一行内容的程序,也就是表头,最后重新写入同名的文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import csv, os
os.makedirs('headerRemoved', exist_ok=True)
写入该文件夹. for csvFilename in os.listdir('.'): if not csvFilename.endswith('.csv'): continue
print('Removing header from ' + csvFilename + '...')
csvRows = [] csvFileObj = open(csvFilename) readerObj = csv.reader(csvFileObj) for row in readerObj: if readerObj.line_num == 1: continue csvRows.append(row) csvFileObj.close()
csvFileObj = open(os.path.join('headerRemoved', csvFilename), 'w', newline='') csvWriter = csv.writer(csvFileObj) for row in csvRows: csvWriter.writerow(row) csvFileObj.close()
|
REFERENCES