python - 我不明白为什么我不能让 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)
推荐阅读
- spring-boot - Spring Boot:使用 JPA 想要从表中获取唯一值
- python-3.x - 在 Python 3 中对字典进行子集化
- algorithm - 无法理解 Closest-Pair 分治算法
- android - 如何提高在 AsyncTask 中从 Internet 检索数据的速度?
- android - 在 listview 中搜索只会刷新整个列表,不会将结果放入列表中
- latex - 按一次删除时删除 Overleaf 中的 2 个空格 [Latex]
- asp.net-mvc-4 - 计算列的实体框架代码优先迁移
- r - 从 XML 抓取 R 网页
- css - 如何使用 Bootstrap 4 更改打印边距?
- python - 为什么终端中的runserver命令不会运行?我(一个完整的初学者)正在使用 Django 构建一个 Web 应用程序(学习日志)