Python read() 函数返回空字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16374425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python read() function returns empty string
提问by Francesco R.
If I type this in Python:
如果我在 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?
有时它以字符串形式返回文件的确切内容,有时它返回一个空字符串(即使文件不为空)。有人可以解释这取决于什么吗?
回答by Martijn Pieters
From the file.read()methoddocumentation:
从file.read()方法文档:
An empty string is returned when EOF is encountered immediately.
当立即遇到 EOF 时返回一个空字符串。
You have hit the end of the file object, there is no more data to read. Files maintain a 'current position', a pointer into the file data, that starts at 0 and is incremented as you read dada.
您已到达文件对象的末尾,没有更多数据可供读取。文件维护一个“当前位置”,一个指向文件数据的指针,它从 0 开始,并在您读取数据时递增。
See the file.tell()methodto read out that position, and the file.seek()methodto change it.
请参阅file.tell()方法读出那个位置,和file.seek()方法去改变它。
回答by pradyunsg
When you reach the end of file (EOF) , the .readmethod returns '', as there is no more data to read.
当您到达文件末尾 (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.'
Note: If this happens at the first time you read the file, check that the file is not empty. If it's not try putting
file.seek(0)before theread.
注意:如果第一次读取文件时发生这种情况,请检查文件是否为空。如果它不尝试把
file.seek(0)前read。
回答by Ulrich Eckhardt
There is another issue, and that is that the file itself might be leaked and only reclaimed late or even never by the garbage collector. Therefore, use a with-statement:
还有另一个问题,那就是文件本身可能会被泄露,并且垃圾收集器只能延迟回收甚至永远不会回收。因此,使用 with 语句:
with open(...) as file:
data = file.read()
This is hard to digest for anyone with a C-ish background (C, C++, Java, C# and probably others) because the indention there always creates a new scope and any variables declared in that scope is inaccessible to the outside. In Python this is simply not the case, but you have to get used to this style first...
对于具有 C 语言背景(C、C++、Java、C# 和可能其他)的任何人来说,这很难理解,因为那里的缩进总是会创建一个新的范围,并且外部无法访问在该范围内声明的任何变量。在 Python 中,情况并非如此,但您必须先习惯这种风格......

