首页 > 解决方案 > 我不明白为什么我不能让 python 中的 readline 函数在这个程序中工作。我究竟做错了什么?

问题描述

在这个程序中,我想将单独的行保存到一个变量中,但是当我尝试打印该变量时,它只返回一个空格,而不是文件中行上的内容。抱歉,我对编程很陌生

file=open('emails.txt','w+')
while True:

    email=input('pls input your email adress: ')
    file.write(email)
    file.write('\n')
    more=input('would you like more emails to be processed? ')
    if more == 'yes' or more == 'ye' or more == 'y' or more == 'yep' or more == 'Y':
        continue

    elif more == 'no' or more == 'nah' or more == 'n' or more == 'N' or more == 'nope':
        file.close()
        print('this is the list of emails so far')
        file=open('emails.txt','r')
        print(file.read()) #this reads the whole file and it works
        email_1=file.readline(1) #this is meant to save the 1st line to a variable but doesn't work!!!
        print(email_1) #this is meant to print it but just returns a space
        file.close()
        print('end of program')

标签: python

解决方案


首先,您应该使用with来处理文件。

其次,您打开文件进行打印并阅读其所有内容:print(file.read())

在这一行之后,光标位于文件末尾,因此下次尝试从文件中读取内容时,会得到空字符串。

要修复它,您几乎没有其他选择。

第一个选项:

添加 file.seek(0, 0)以将光标移回文件的开头,因此当您这样做时file.readline,您将真正读取文件行。

此外,file.readline(1)应改为file.readline()

第二种选择:

只需将所有文件内容读入列表,打印它然后打印列表中的第一个条目(文件中的第一行......)

file = open('emails.txt', 'r')
content = file.readlines()
print(*content, sep='')
email_1 = content[0] 
print(email_1)  

推荐阅读