python - 如何将结果保存到文件中?
问题描述
我目前无法找到将结果保存在我通过 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))
推荐阅读
- c - 如何使用 g_signal_handlers_block_by_func()
- python - 在正则表达式匹配的字符中仅捕获相同的字符
- c# - 如何修复 ASMX Web 服务中的 XML 序列化问题
- winforms - 如何在 WCF 中引发 GUI 事件?
- oauth-2.0 - 无法让 Linkedin 从 socialActions v2 端点返回数据
- java - 在java游戏中为多个实体设置方向的问题
- scala - 获取 Scala 类对象中具有值的所有公共字段
- jquery - 带有 JQuery 的下拉 json 数据显示“未定义”结果
- python - python命令行程序作为字符串抛出错误传入
- .net - WPF 更改 ItemContainerStyle 但保留引用的基本样式