2017-05-08 152 views
-1

为什么当read()到达文件末尾时会返回空字符串;这个空字符串显示为空行。我知道我们可以使用rstrip()将其删除。Python,read()文件末尾的空字符串

+1

http://stackoverflow.com/questions/16374425/python-read-function-returns-empty-string –

+3

它在文件末尾返回一个空字符串,因为文件末尾没有文本 –

+0

可能[Python读取()函数返回空字符串]的副本(http://stackoverflow.com/questions/16374425/python-read-function-returns-empty-string) – WhatsThePoint

回答

1

read()方法返回空字符串,因为您已到达文件的结尾并且文件中没有更多文本。

f = open('f.txt') print f.read() print f.tell()

这里f.tell()会给你的搜索位置,当你做f.tell()这将是在文件的结尾,并返回该文件的长度。

0

我有这个问题一段时间,我一直在寻找这个问题的答案。我最近找到了解决方案。

必须设置.read()为字符串

这将工作:

read_file = open("file.txt", "r") 

file_string = read_file.read() 

print(file_string) 

read_file.close() 

我希望这有助于。它为我工作,所以我相信它会为你工作。