在通过csv阅读器运行之前,如何编辑打开的csv文件的内容?
$ python -c "import news_module"
这不能正常工作,csv.reader仍然会读取旧的未经编辑的文件。
我该如何解决这个问题?
答案 0 :(得分:1)
您可以构建生成器以允许动态编辑csv
文件。这实际上并不编辑文件,它只是修改了csv
读者看到的内容。
<强>代码:强>
def edit_csv_on_fly(csv_file):
for line in csv_file.readlines():
# replacing comma with semicolon
yield line.replace(",", ";")
测试代码:
import csv
with open('myfile.csv', 'rU') as csvfile:
csv_read = csv.reader(
edit_csv_on_fly(csvfile), delimiter=";", quotechar='"')
for row in csv_read:
print(row)
测试数据:
"COLUMN A","COLUMN B","COLUMN C","COLUMN D","COLUMN E"
"COLUMN A","COLUMN B","COLUMN C","COLUMN D","COLUMN E"
"COLUMN A","COLUMN B","COLUMN C","COLUMN D";"COLUMN E"
<强>结果:强>
['COLUMN A', 'COLUMN B', 'COLUMN C', 'COLUMN D', 'COLUMN E']
['COLUMN A', 'COLUMN B', 'COLUMN C', 'COLUMN D', 'COLUMN E']
['COLUMN A', 'COLUMN B', 'COLUMN C', 'COLUMN D', 'COLUMN E']