为什么用Python读取.txt文件会导致控制台中出现空行?

2024-04-26 02:49:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读一个.txt文件的教程的一部分。我按照指令键对键操作,但我的控制台日志返回一个空行

有人知道会发生什么吗

employee_file = open('employees.txt', 'r')

print(employee_file.readline())

employee_file.close()

Tags: 文件txtclosereadline指令employee教程open
3条回答

可能在同一控制台会话中,您已经打开并读取了文件,但忘记关闭它。然后重新运行相同的readlinereadlines(),返回空,因为文件指针已经在文件末尾

$ cat employees.txt
Jim-Sales
111
222

$ python3.7
Python 3.7.2 (default, Mar  8 2019, 19:01:13) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> employee_file = open('employees.txt', 'r')
>>> print(employee_file.readline())
Jim-Sales

>>> print(employee_file.readlines())
['111\n', '222\n']
>>> 
>>> 
>>> 
>>> print(employee_file.readline())

>>> print(employee_file.readlines())
[]

这就是为什么建议的做法是始终wrap it in a ^{} statement

>>> with open("employees.txt", "r") as employee_file:
...      print(employee_file.readlines())
... 
['Jim-Sales\n', '111\n', '222\n']
>>> with open("employees.txt", "r") as employee_file:
...      print(employee_file.readlines())
... 
['Jim-Sales\n', '111\n', '222\n']

首先,确保您在文件所在的同一路径中工作, 使用以下命令: 打印(os.getcwd()) 其次,确保文件不是空的并保存它。 第三,使用@bashbelam编写的代码,它应该可以工作

我希望这对你有帮助

试着这样做:

with open ('employees.txt') as file :
    for line in file :
        print (line)

相关问题 更多 >