简体   繁体   中英

Append lines from a text file to a list in python without '\n'

I'm currently learning python and I have a login system that uses a text file called "users" to store the usernames. I want to be able to update this file by reading the text line by line and appending it to an array in python. Then writing the array back into the text file to be appended into the array again the next time I open the program.

But right now, as each username is written in different lines, when I append it to my array it gives me:
username = ['testing1\n', 'testing2']

this is my code:

import random
import operator
import shelve
import os
from os import system, name 
import time
from time import sleep

users = []
password = []

def clear():
    if name == 'nt':
        _ = system('cls')
    else:
        print("thisisweird.")

# start of login system

def loggedOut():
    status = input("Are you a registered user? y/n? Press q to quit ")
    if status == "y":
        oldUser()

    elif status == "n":
        newUser()

    elif status == "q":
        quit()


def loggedIn():
    menu()

def newUser():
    createLogin = input('Create a Username: ')
    
    if createLogin in users:
        print("\nUsername is taken")
    else:
        users.append(createLogin)
        createPwd = input("Create a Password: ")
        password.append(createPwd)
        print("\nRegister successful\n")
        loggedOut()

def oldUser():
    login = input("Enter username: ")
    pwd = input("Enter password:")

    if login in users and users[login] == pwd:
        print("\nWelcome,", login,"!")
        loggedIn()
    else:
        print("\nUsername or Password invalid\n")

def quit():
    print("Goodbye! The program will now exit")
    os.remove('./users/login.txt')
    f = open('./users/login.txt', 'w')
    for ele in users:
        f.write(ele+'\n')
    f.close()
    sleep(2)
    clear()
    exit()

#end of login system 

def loginsys():
    folder_check = os.path.isdir('./users')
    if (folder_check == True):
        file_check = os.path.isfile('./users/login.txt')
        if (file_check == True):
            f = open('./users/login.txt', 'r+')
            f1 = f.readlines()
            for ele in f1:
                users.append(ele)
            f.close()
            print(users)
            loggedOut()
        else:
            f = open('./users/login.txt', 'w')
            f.write('')
            f.close()
            loggedOut()
    else:
        os.mkdir('./users') 
        loginsys()

def menu():
    print("Hello World")

loginsys()

readlines() puts a newline at the end of every text line. You can use rstrip() to remove it:

f = open('./users/login.txt', 'r+')
f1 = f.readlines()
for ele in f1:
    users.append(ele.rstrip())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM