将文本文件中的行附加到 python 中的列表,不带 '\n'

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

我目前正在学习 python 并且我有一个登录系统,它使用名为“users”的文本文件来存储用户名。我希望能够通过逐行读取文本并将其附加到 python 中的数组来更新此文件。然后将数组写回文本文件,下次打开程序时再次追加到数组中。

但是现在,由于每个用户名都写在不同的行中,当我将其附加到我的数组时,它会给我:
username = ['testing1\n', 'testing2']

这是我的代码:

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() 在每个文本行的末尾放置一个换行符。您可以使用 rstrip() 删除它:

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