简体   繁体   English

f.read空了

[英]f.read coming up empty

I'm doing all this in the interpreter.. 我正在翻译中执行所有操作。

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

at this point i can do file1.read() and it prints the file's contents as a string to standard output 此时,我可以执行file1.read(),它将文件的内容作为字符串打印到标准输出中

but if i add this.. 但是如果我添加这个..

string1 = file1.read()

string 1 comes back empty.. i have no idea what i could be doing wrong. 字符串1返回为空..我不知道我可能做错了。 this seems like the most basic thing! 这似乎是最基本的事情!

if I go on to type file1.read() again, the output to standard output is just an empty string. 如果我再次输入file1.read(),则标准输出的输出只是一个空字符串。 so, somehow i am losing my file when i try to create a string with file1.read() 所以,当我尝试用file1.read()创建一个字符串时,我以某种方式丢失了我的文件

You can only read a file once. 您只能读取一次文件。 After that, the current read-position is at the end of the file. 之后,当前的读取位置在文件的末尾。

If you add file1.seek(0) before you re-read it, you should be able to read the contents again. 如果在重新读取前添加了file1.seek(0) ,则应该能够再次读取其内容。 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

You do not lose it, you just move offset pointer to the end of file and try to read some more data. 您不会丢失它,只需将偏移指针移到文件末尾并尝试读取更多数据。 Since it is the end of the file, no more data is available and you get empty string. 由于它是文件的结尾,因此不再有可用的数据,并且您会得到空字符串。 Try reopening file or seeking to zero position: 尝试重新打开文件或寻求零位:

f.read()
f.seek(0)
f.read()

Using with is the best syntax to use because it closes the connection to the file after using it(since python 2.5): 使用with是最好的语法,因为使用后它会关闭与文件的连接(自python 2.5起):

with open('/council/council1', 'r') as input_file:
   text = input_file.read()
print(text)

make sure your location is correct. 确保您的位置正确。 Do you actually have a directory called /council under your root directory ( / ) ?. 根目录( / )下是否确实有一个名为/council的目录? also use, os.path.join() to create your path 还使用os.path.join()创建路径

loc1 = os.path.join("/path","dir1","dir2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM