文本文件在Windows上的Python中使用readline()返回空白[重复]

问题描述 投票:0回答:2
我在本教程的中间,它的任务似乎很简单,即读取文件,但是其中一种检查文件的测试似乎失败了。

employee_file = open("employees.txt", "r") print(employee_file.readable()) # this returns "True" to the screen print(employee_file.read()) # this reads out the file to screen, as is. print(employee_file.readline()) # this returns a blank line print(employee_file.readlines()) # this returns blank brackets. employee_file.close()

我的输出窗口显示以下内容:

runfile('C:/Users/bsimmons/Documents/Python Scripts/reading_files_prac.py', wdir='C:/Users/bsimmons/Documents/Python Scripts') True Jim - Salesman Dwight - Salesman Pam - Receptionist Michael - Manager Oscar - Accountant Bruce - Scientist . .. []

我在Windows 10笔记本电脑上,正在使用Spyder 4.01,Python 3.7和Chrome来运行我的视频教程。

该txt文件与我的脚本位于同一目录中,并且文件中的文本如下所示:

Jim - Salesman Dwight - Salesman Pam - Receptionist Michael - Manager Oscar - Accountant Bruce - Scientist

我已经测试了文件,Python说它不为空。我在最后一行之后添加了空行,但无济于事。我已经用测试代码列出了目录,它们显示文件在那里。

如果我换出

print(employee_file.readlines())

with

print(employee_file.readlines()[1])

我得到list index out of range.

我束手无策,因为我觉得经过几个小时的研究,我似乎在任何地方都找不到合适的答案来解决这个看似简单的测试打印纸。或者当我拍打我的脸时,我还没有意识到这个修复方法。

python windows file-handling readline
2个回答
0
投票
employee_file = open("employees.txt", "r") print(employee_file.readable()) print(employee_file.read()) employee_file.seek(0) # Sets the reference point at the beginning of the file print(employee_file.readline()) print(employee_file.readlines()) employee_file.close()

0
投票
一旦您read()该文件,您将无法再读取它。而且,一旦您readline(),您将无法再读取该行,但您将在其后读取该行。

读取文件就像指向文件中特定位置的指针,一旦您读取该位置,该指针将指向下一个位置,直到到达文件末尾。

因此,一旦read()文件被读取,指针将指向下一个位置(文件结尾),然后将打印该文件。

如果要再次读取文件(使指针再次指向文件的开头),则必须使用

employee_file.seek(0)

根据this question
© www.soinside.com 2019 - 2024. All rights reserved.