文件看起来像这样:
2014-01-01 a a a
2014-01-01 a a
2014-01-01 a a
我想浏览所有行并在空行中添加NoData
:
输出应该如下所示:
2014-01-01 a a a
2014-01-01 a NodData a
2014-01-01 a a NoData
我应该用csv reader
打开文件而不是遍历所有行吗?如何定义空单元格/行
答案 0 :(得分:1)
import csv
with open('path/to/input') as infile, open('path/to/input', 'w') as fout:
outfile = csv.writer(fout)
for row in csv.reader(infile):
row = [cell if cell else 'NoData' for cell in row]
outfile.writerow(row)
如果要覆盖输入文件:
import csv
with open('path/to/input') as infile: rows = list(csv.reader(infile))
with open('path/to/input', 'w') as fout:
outfile = csv.writer(fout)
for row in ([cell if cell else 'NoData' for cell in row] for row in rows)
outfile.writerow(row)
如果要对目录中的所有csv文件执行此操作:
import csv
import glob
import os
dirpath = "/Users/Kevin/Desktop/DataArena/"
for infilepath in glob.glob(os.path.join(dirpath, "*.csv")):
with open(infilepath) as infile: rows = list(csv.reader(infile))
with open(infilepath, 'w') as fout:
outfile = csv.writer(fout)
for row in ([cell if cell else 'NoData' for cell in row] for row in rows)
outfile.writerow(row)