使用csv module https://docs.python.org/2/library/csv.html, plus itertools.islice() https://docs.python.org/2/library/itertools.html#itertools.islice每次选择 3 行:
import csv
import os.path
from itertools import islice
with open(inputfilename, 'rb') as infh:
reader = csv.reader(infh)
for row in reader:
filename = row[0].replace(' ', '_') + '.csv')
filename = os.path.join(directory, filename)
with open(filename, 'wb') as outfh:
writer = csv.writer(outfh)
writer.writerow(row)
writer.writerows(islice(reader, 2))
The writer.writerows(islice(reader, 2))
line 首先将当前行(带有日期)写入输出文件后,从读取器获取接下来的 2 行,将它们复制到写入器 CSV。
您可能需要调整delimiter
论证csv.reader()
and csv.writer()
物体;默认是逗号,但您没有指定确切的格式,也许您需要将其设置为'\t'
选项卡代替。
如果您使用的是 Python 3,请使用以下命令打开文件'r'
and 'w'
文本模式,并设置newline=''
对彼此而言;open(inputfilename, 'r', newline='')
and open(filename, 'w', newline='')
.