如何将结果保存到文件中?

Jer*_*Lin 3 python csv for-loop python-3.x

我目前在麻烦一种方法来将结果保存到通过sys.argv [1]提供的文件中。我向python脚本提供了csv。

我的csv具有这样的格式的数据

3/4/20

3/5/20

3/6/20
Run Code Online (Sandbox Code Playgroud)

我尝试使用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)
Run Code Online (Sandbox Code Playgroud)

任何帮助是极大的赞赏!

Joh*_*opp 5

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

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))
Run Code Online (Sandbox Code Playgroud)