gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:59 29 4
gpt4 key购买 nike

我目前无法找到一种方法来将结果保存在我通过 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)

非常感谢任何帮助!

最佳答案

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

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))

关于python - 如何将结果保存到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58458005/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com