Python read() 函数返回空字符串

标签 python file-io

<分区>

如果我在 Python 中输入:

open("file","r").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.'

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

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 the read.

关于Python read() 函数返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374425/

相关文章:

java - 逐行写入文本文件

c - 使用 fscanf 时出现段错误

python - python/pythonpath 路径问题

python - python 2 函数在没有任何导入的情况下运行所需的时间;是否可以?

python - 如何找到数组中最常见的元素

java - 使用 Unicode 文件路径

python - 在 Windows 上使用 PyCharm 的 matplotlib 不会绘制图形,没有错误

python - Pandas 与多个值变量一起融化

vba - 我如何一个一个打开所有的excel文件并运行一个宏

java - FileInputStream 为空?