首页 > 解决方案 > 如何将结果保存到文件中?

问题描述

我目前无法找到将结果保存在我通过 sys.argv[1] 提供的文件中的方法。我正在为 python 脚本提供一个 csv。

我的 csv 有这样格式的数据

3/4/20

3/5/20

3/6/20

我尝试使用 append() 但收到错误,我也尝试使用 write()

import sys

file = open(str(sys.argv[1])) #enter csv path name, make sure the file only contains the dates
for i in file:
    addedstring = (i.rstrip() +',09,00, 17')
    finalstring = addedstring.replace("20,", "2020,")

file.append(i)

任何帮助是极大的赞赏!

标签: pythonpython-3.xcsvfor-loop

解决方案


一种选择是将修改后的字符串放入列表中,然后关闭文件,重新打开以进行写入,然后写入修改后的字符串列表:

finalstring = []
with open(sys.argv[1], "r") as file:
    for i in file:
        addedstring = (i.rstrip() +',09,00, 17')
        finalstring.append(addedstring.replace('20,', '2020,'))
with open(sys.argv[1], "w") as file:
    file.write('\n'.join(finalstring))

推荐阅读