f.read空了 [英] f.read coming up empty

查看:52
本文介绍了f.read空了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解释器中做所有这些事情.

I'm doing all this in the interpreter..

loc1 = '/council/council1'
file1 = open(loc1, 'r')

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

at this point i can do file1.read() and it prints the file's contents as a string to standard output

但是如果我添加这个..

but if i add this..

string1 = file1.read()

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

string 1 comes back empty.. i have no idea what i could be doing wrong. this seems like the most basic thing!

如果我再次输入file1.read(),则标准输出的输出只是一个空字符串.所以,当我尝试使用file1.read()

if I go on to type file1.read() again, the output to standard output is just an empty string. so, somehow i am losing my file when i try to create a string with file1.read()

推荐答案

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

You can only read a file once. After that, the current read-position is at the end of the file.

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

If you add file1.seek(0) before you re-read it, you should be able to read the contents again. A better approach, however, is to read into a string the first time and then keep it in memory:

loc1 = '/council/council1'
file1 = open(loc1, 'r')
string1 = file1.read()
print string1

这篇关于f.read空了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆