我在文件read中使用next是为了解析数据而不是头行,因此read完全避免了第一行。如何在读操作(而不是解析标题行)中提取标题,然后在写操作中写入标题?你知道吗
我要对的实际数据集是30col和80k行,所以我尝试在一次读取操作中完成这个操作。你知道吗
试验数据:
date, animal, color
3/14/2015, cat, blue
3/24/2015, dog, green
代码:
from dateutil.parser import *
import csv
with open('testin.csv', 'r', encoding='utf-8') as inFile, open('testout.csv', 'w', encoding='utf-8') as outFile:
exampleReader = csv.reader(inFile)
next(exampleReader, 1)
exampleData = list(exampleReader)
exampleWriter = csv.writer(outFile)
# print a few to see what it's doing
print('the list', exampleData)
for item in exampleData:
item[0] = str(parse(item[0])) # converting date format for sqlite
del item[2] # dropping column that is not needed
print('date corrected', item)
exampleWriter.writerow(item)
在处理输入文件的其余部分之前写入头文件:
我重新安排了一些事情,但是,主要的一点是将头读入带有
next()
的变量,从头中删除不需要的列,然后将其写入输出文件。然后处理输入文件的其余部分。你知道吗重要的一点是,输入文件的其余部分在for循环中逐行处理。当您可以对整个文件进行迭代时,不必预先将其读入列表。你知道吗
还可以使用生成器表达式高效地写入行:
我会使用pandas来处理这样大量的数据:
示例:
相关问题 更多 >
编程相关推荐