0

So, I'm making a password generator and trying to save it to a text file. This is how it looks:

import string
from random import *

characters = string.ascii_letters + string.punctuation  + string.digits
password =  ("".join(choice(characters) for x in range(randint(8, 16))))
print(password)

choice = input("What is your password for?")
F = open("Passwords.py", "w")
F.write("\n" + choice + ": " + password)
F.close()

But for some reason, the text file only saves the most recent password. And for this to actually be applicable, I need the text file to save more than one password. Is there any way to prevent this?

2 Answers2

0

When you are doing open("Passwords.py", "w") the W for write is overwriting the existing file data you can use open("Passwords.py", "a") to append data to the file and this will add you new password without overwriting the existing.
You can do as following

with open("Passwords.py", "a") as f:
    f.write("\n" + choice + ": " + password)

when using with on a file it will close it automatically after executing the write()

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
0

you are using write not append

anything you type will be overwritten

F = open("passwords.txt", "a")
f.append("/n" + choice + ": " + password)