Python在重新打开后编辑.csv [复制](Python edits .csv after reopening [duplicate])

编程入门 行业动态 更新时间:2024-10-26 04:26:30
Python在重新打开后编辑.csv [复制](Python edits .csv after reopening [duplicate])

这个问题在这里已经有了答案:

你如何追加到一个文件? 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 answers

I 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

更多推荐

本文发布于:2023-07-04 10:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023514.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:编辑   csv   Python   duplicate   reopening

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!