编辑打开的csv文件

时间:2017-04-08 19:07:18

标签: python csv generator

在通过csv阅读器运行之前,如何编辑打开的csv文件的内容?

$ python -c "import news_module"

这不能正常工作,csv.reader仍然会读取旧的未经编辑的文件。

我该如何解决这个问题?

1 个答案:

答案 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']