这个问题在这里已经有了答案:
你如何追加到一个文件? 7个答案我想创建一个表单,您可以在其中填写输入,并将数据保存在.csv文件中。 但是,如果我关闭脚本并再次打开它,添加更多的entrys,那么它会删除我的.csv文件中的旧版本。 我怎样才能添加新的信息,它不会删除旧信息。 如果这是不可能的,我如何创建一个随机文件名称,如:mydata_random.csv?
剧本:
import sys try: d = open("mydata.csv" , "w") except: print("Couldn't open the file") sys.exit(0) li = [1, "John Doe", "xxx"] d.write(str(li[0]) + ";" + li[1] + ";" + str(li[2]).replace(".",",") + "\n") dli = [[2, "John Doe" , "yyy"], [3, "John Doe", "zzz"]] for element in dli: d.write(str(element[0]) + ";" + element[1] + ";" + str(element[2]).replace(".",",") + "\n") d.close()This question already has an answer here:
How do you append to a file in Python? 10 answersI want to create a form, where you can fill in an input and it will saves the data in a .csv file. But if I close the script and open it again, to add more entrys, then it delets the old entrys in my .csv file. How can I add new informations, that it doesn't deletes the old ones. If that isn't possible, how can I create a random file name like: mydata_random.csv ?
The script:
import sys try: d = open("mydata.csv" , "w") except: print("Couldn't open the file") sys.exit(0) li = [1, "John Doe", "xxx"] d.write(str(li[0]) + ";" + li[1] + ";" + str(li[2]).replace(".",",") + "\n") dli = [[2, "John Doe" , "yyy"], [3, "John Doe", "zzz"]] for element in dli: d.write(str(element[0]) + ";" + element[1] + ";" + str(element[2]).replace(".",",") + "\n") d.close()最满意答案
问题是打开文件时使用的模式。
d = open("mydata.csv" , "w")使用模式w ,它将在每次保存时覆盖文件。
d = open("mydata.csv" , "a")使用模式a ,它将在每次保存时附加到文件。
你可以阅读更多关于在这里打开的其他模式: https : //docs.python.org/2/library/functions.html#open
The issue is the mode you use when opening the file.
d = open("mydata.csv" , "w") uses mode w which will overwrite the file on each save.
d = open("mydata.csv" , "a") uses the mode a which will append to the file on each save.
You can read more about the other modes of open here: https://docs.python.org/2/library/functions.html#open
更多推荐
发布评论