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

Why does reading a .txt file with Python results in a blank line in the console?

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

有谁知道什么可以关闭?

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

print(employee_file.readline())

employee_file.close()

这样试试:

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

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

希望对你有所帮助

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

$ 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 with 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']

使用文件对象的seek()函数。

这会将文件的当前位置设置为偏移量,可能是您文件中的光标位于最后一个位置,因此您什么也得不到。

更新您的代码:

employee_file = open('employees.txt', 'r')
employee_file.seek(0)  # Sets cursor in your file at absolute position (At beginning)

print(employee_file.readline())

这应该有效。