W
W
Wet_Dumplings2018-09-06 08:42:27
Python
Wet_Dumplings, 2018-09-06 08:42:27

How to write more than 1 line to .txt file?

Hey!
I tried to make authentication in python with differentiation of user rights (0-user, 1-admin), but when I try to write more than 1 user, the old line is overwritten.
format: login password rights

def create_user():
    print('создание пользователя, введите: [логин] [пароль] [права]')
    my_file = open("logbase.txt", "w")
    inp = input()
    my_file.write(inp+"\n")
    my_file.close()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
techkuz, 2018-09-06
@Wet_Dumplings

def create_user():
    print('создание пользователя, введите: [логин] [пароль] [права]')
    my_file = open("logbase.txt", "a")
    inp = input()
    my_file.write(inp + "\n")
    my_file.close()

You have the w flag on open, which overwrites the file. The a flag will append (append to the end, instead of overwriting)
I recommend refactoring the code as follows:
def create_user():
    print('создание пользователя, введите: [логин] [пароль] [права]')
    with open("logbase.txt", "a") as myfile:
        inp = input()
        my_file.write(inp+"\n")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question