f.read空了

Par*_*yon 2 python string file

我在翻译中做了这一切......

loc1 = '/council/council1'
file1 = open(loc1, 'r')
Run Code Online (Sandbox Code Playgroud)

此时我可以执行file1.read()并将文件的内容作为字符串打印到标准输出

但如果我加上这个..

string1 = file1.read()
Run Code Online (Sandbox Code Playgroud)

字符串1回来了空..我不知道我可能做错了什么.这似乎是最基本的东西!

如果我继续再次输入file1.read(),则输出到标准输出只是一个空字符串.所以,当我尝试使用file1.read()创建一个字符串时,我失去了我的文件

Zoo*_*oba 5

您只能读取一次文件.之后,当前读取位置位于文件的末尾.

如果file1.seek(0)在重新阅读之前添加,则应该能够再次阅读内容.然而,更好的方法是第一次读入字符串然后将其保存在内存中:

loc1 = '/council/council1'
file1 = open(loc1, 'r')
string1 = file1.read()
print string1
Run Code Online (Sandbox Code Playgroud)