Dark Ariel7
Dark Ariel7

Reputation: 39

how to stop python from wipping my text file clean -python 3

I am writing a simple script to add users and a password to a text file. I managed to figure it out but ran into the unexpected problem of my file being wiped clean each time with only my recent add in the text file. Here is the code

from getpass import getpass
from time import sleep

def Add_User():
    Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", "w", encoding='utf-8')
    Username = input("Username: ")
    Password = getpass(str("Password: "))
    Add_User = ",".join((Username,Password))
    Database.write(Add_User)

Add_User()

I also appreciate extra feedback.

Upvotes: 0

Views: 194

Answers (1)

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

Use the append "a" option instead of the write option "w".

Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", "a", encoding='utf-8')

From The Docs,

'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position)

P.S - You could also use raw strings instead of manually escaping the \ character.

Also, use the with statement when dealing with files, the context manager ensures that your file is closed.

Upvotes: 4

Related Questions