How to write in CSV and not overwrite past text

The code below is what I have. When it writes to .csv, it overwrites what I previously wrote in the file. How can I write a file so that it does not delete my previous text. (The purpose of my code is to have a person enter their name and remember their program)

def main(src): try: input_file = open(src, "r") except IOError as error: print("Error: Cannot open '" + src + "' for processing.") print("Welcome to Learner!") print("What is your name? ") name = input() for line in input_file: w = line.split(",") for x in w: if x.lower() == name.lower(): print("I remember you "+ name.upper()) else: print("NO") a = open("learner.csv", "w") a.write(name) a.close() break if __name__ == "__main__": main("learner.csv") 
+4
source share
3 answers

You need to add the file next time. This can be done by opening the file in upload mode.

 def addToFile(file, what): f = open(file, 'a').write(what) 
+5
source

change open("learner.csv", "w") to open("learner.csv", "a")

The second parameter with open is mode, w is write, and add. Using append, it automatically searches for the end of the file.

+6
source

You need to open the file in append-mode ('a'), rathen than write-mode ('w'); The Python documentation explains the various modes available.

In addition, you may need to use the with keyword:

It is good practice to use the s keyword when working with file objects. This has the advantage that the file is closed correctly after completing typing, even if an exception occurs in the path.

 >>> with open('/tmp/workfile', 'a') as f: ... f.write(your_input) 
+4
source

Source: https://habr.com/ru/post/1443748/


All Articles