10

If I type this in Python:

open("file","r").read()

sometimes it returns the exact content of the file as a string, some other times it returns an empty string (even if the file is not empty). Can someone explain what does this depend on?

4

3 回答 3

34

当您到达文件末尾 (EOF) 时,该.read方法返回'',因为没有更多数据要读取。

>>> f = open('my_file.txt')
>>> f.read() # you read the entire file
'My File has data.'
>>> f.read() # you've reached the end of the file 
''
>>> f.tell() # give my current position at file
17
>>> f.seek(0) # Go back to the starting position
>>> f.read() # and read the file again
'My File has data.'

文档链接:read() tell() seek()

注意:如果在您第一次读取文件时发生这种情况,请检查文件是否为空。如果不是尝试file.seek(0)放在read.

于 2013-05-04T12:47:49.900 回答
8

file.read()方法文档:

立即遇到 EOF 时返回一个空字符串。

您已经到达文件对象的末尾,没有更多数据要读取。文件维护一个“当前位置”,一个指向文件数据的指针,它从 0 开始,并随着您读取数据而递增。

请参阅读取该位置的file.tell()方法以及更改它的file.seek()方法。

于 2013-05-04T12:44:45.933 回答
3

还有另一个问题,那就是文件本身可能会被泄露,并且垃圾收集器只能延迟回收,甚至永远不会回收。因此,使用 with 语句:

with open(...) as file:
    data = file.read()

对于具有 C-ish 背景(C、C++、Java、C# 和可能其他)的任何人来说,这很难理解,因为那里的缩进总是会创建一个新的范围,并且在该范围内声明的任何变量都是外部无法访问的。在 Python 中,情况并非如此,但你必须先习惯这种风格......

于 2013-05-04T14:05:00.257 回答