0

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.

Dark Ariel7
  • 39
  • 1
  • 8
  • 1
    Extra feedback: 1: What happens when the user enters "doe,john" as a username? 2: Please read the [Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/). 3: Use _with_ to open files. – Matthias Aug 08 '13 at 17:33
  • I don't understand your question. Also why do I need this guide? – Dark Ariel7 Aug 08 '13 at 23:10
  • I forgot to mention that I have yet to learn with statements. – Dark Ariel7 Aug 08 '13 at 23:18

1 Answers1

4

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.

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
  • what do you mean raw strings? Also how do I space or format what I print? – Dark Ariel7 Aug 08 '13 at 19:03
  • @DarkAriel7 : Read up raw strings in [this question](http://stackoverflow.com/questions/4780088/in-python-what-does-preceding-a-string-literal-with-r-mean). Also, for formatting use the `format(...)` function available in Python. – Sukrit Kalra Aug 08 '13 at 19:06
  • That is not entirely what I meant. I want to know how to make it a separate line. As in the new user password combo on a different line than the previous combo. – Dark Ariel7 Aug 08 '13 at 23:11