【问题标题】:How do I save the results into the file?如何将结果保存到文件中?
【发布时间】:2020-02-15 20:57:13
【问题描述】:

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

非常感谢任何帮助!

【问题讨论】:

  • 需要更清楚地了解您想要实现的目标。您是在尝试读取 csv 还是尝试将数据写入 csv?

标签: python python-3.x csv for-loop


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多