Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将结果保存到文件中?_Python_Python 3.x_Csv_For Loop - Fatal编程技术网

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

Python 如何将结果保存到文件中?,python,python-3.x,csv,for-loop,Python,Python 3.x,Csv,For Loop,我目前在通过sys.argv[1]提供的文件中无法找到保存结果的方法。我正在为python脚本提供csv 我的csv有如下格式的数据 3/4/20 3/5/20 3/6/20 我尝试过使用append(),但收到错误,我也尝试过使用write() 非常感谢您的帮助 一个选项是将修改后的字符串放入列表,然后关闭文件,重新打开进行写入,然后写入修改后的字符串列表: finalstring = [] with open(sys.argv[1], "r") as file: for i i

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

我的csv有如下格式的数据

3/4/20

3/5/20

3/6/20
我尝试过使用append(),但收到错误,我也尝试过使用write()


非常感谢您的帮助

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

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

需要更清楚地了解你想要实现的目标。您是尝试读取csv还是尝试将数据写入csv?
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))