我不明白为什么我不能让 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')

首先,您应该使用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)  

正如上面第一条注释中所提到的,file.read((调用将文件指针移动到文件的末尾,因此没有数据可供readline((读取。

但是,您调用的是readline(1(,它将读取一个字节,而不是一行。

我会尝试使用with

所以试着这样实现它:

> with open('emails.txt','w+') as output_file:  
while True:
# and then rest of your code

相关内容

最新更新