简体   繁体   English

如何从文本文件中的不同行写入和读取?

[英]How to write and read from different lines in a text file?

I have a very simple 'login' program that I've almost got finished.我有一个几乎完成的非常简单的“登录”程序。 I'm trying to get my make_acc() function to write the username on line 1 and the password on line 2, as well as make my login() function read those separate lines per what needs to be checked.我试图让我的make_acc() function 在第 1 行写入用户名,在第 2 行写入密码,并让我的login() function 根据需要检查的内容读取这些单独的行。 I'm pretty sure the answer has to do with marking the readline command for which line needs to be read, but I'm not sure how to implement it in my code properly.我很确定答案与标记需要读取哪一行的 readline 命令有关,但我不确定如何在我的代码中正确实现它。 Here's the code.这是代码。

# This function has the user input a username for their account
def make_acc():
    username = input('Make a username:')
    file = open('acc_data.txt','w')
    file.write(username)
    file.close()
    #password = input('Make a password:')
    #file = open('acc_data.txt','w')
    #file.write(password)

# This function has the user login to a preexisting account
def login():
    input_user = input('Enter your username:')
    file = open('acc_data.txt','r')
    username = file.readline()
    if input_user == username:
        print('You are now logged in')
    else:
        print('That user does not exist')
        login()

# This variable will be defined as a yes or no depending on whether or not the use has an account
acc_bool = input('Do you already have an account?:')

# This if statement runs the login() function if the user answered yes to the previous input
if acc_bool == 'yes':
    login()
# This elif statement runs the make_acc() function if the user answered no to the previous input
elif acc_bool == 'no':
    make_acc()
    login()

This should do it:这应该这样做:

def make_acc():
    username = input('Make a username:')
    password = input('Make a password:')
    with open('acc_data.txt','a') as file:
        file.write(username+'\n')
        file.write(password)

def login():
    input_user = input('Enter your username:')
    with open('acc_data.txt','r') as file:
        if input_user in [u for i,u in enumerate(file.readlines()) if not u%2]:    
            print('You are now logged in')
        else:
            print('That user does not exist')
            login()

Instead of having the usernames and passwords all in 2 lines,而不是将用户名和密码全部放在两行中,
you can use indexes to determine whether a line is a username or password:您可以使用索引来确定一行是用户名还是密码:
even indexes are for usernames, and odd ones are for passwords.偶数索引用于用户名,奇数索引用于密码。


UPDATE:更新:

This part: [u for i,u in enumerate(file.readlines()) if not u%2] lists all the strings in file.readlines() (a list of all the lines in f.read()) if the index of the string, i , doesn't leave a remainder when divided by 2.这部分: [u for i,u in enumerate(file.readlines()) if not u%2]列出 file.readlines() 中的所有字符串( file.readlines()中所有行的列表)如果字符串的索引i除以 2 时不会留下余数。

You see, enumerate() will basically let us iterate through an array and let use easily access the index of the current iteration.你看, enumerate()基本上可以让我们遍历一个数组并让我们轻松访问当前迭代的索引。

First, uncomment the part of make_acc that asks for a password and add a file.close() .首先,取消注释make_acc中要求输入密码的部分并添加file.close()

Then, notice that when you've run the program and inputted the two pieces of information, only one is left in the file, this is because, when calling open() , you use the w mode, which truncates the file before allowing you to write.然后,请注意,当您运行程序并输入两条信息时,文件中只剩下一条,这是因为在调用open()时,您使用的是w模式,它会在允许您之前截断文件来写。 The consequence of this is that when you open the file again a couple of lines later, all information previously stored is lost.这样做的结果是,当您在几行之后再次打开文件时,之前存储的所有信息都会丢失。 The solution is to use mode r+ or a or just not close the file until the end of the function, thereby avoiding having to reopening it when writing the password.解决方案是使用模式r+a或直到 function 结束时才关闭文件,从而避免在写入密码时必须重新打开它。

Next, when reading from the file, you can use file.readline() just as you already are doing.接下来,从文件中读取时,您可以使用file.readline()就像您已经在做的那样。 Choosing what line to read happens by default, because every call to readline advances what line is being read.默认情况下选择要读取的行,因为每次调用 readline 都会推进正在读取的行。 This means that the second time you call it since you opened the file, the second line will be read.这意味着自打开文件后第二次调用它时,将读取第二行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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