0

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()
Ole A
  • 3
  • 3

2 Answers2

1

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

Spence Wetjen
  • 199
  • 1
  • 9
0

The problem here is that you're opening your file in write mode w . The second time or even the first time you open it you need to open it in append mode a

d = open("mydata.csv" , "w")

So this code will become

d = open("mydata.csv" , "wa")

Now you can add as many entries as you want.

Check out the answer to this question should help you

Jaysheel Utekar
  • 1,171
  • 1
  • 19
  • 37