开发者

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

but if i add this..

string1 = file1.read()

string 1 comes back empty.. i have no idea what i could be doing wrong. 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. so, somehow i am losing my file wh开发者_开发问答en 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.

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


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 open('/council/council1', 'r') as input_file:
   text = input_file.read()
print(text)


To quote the official documentation on read():

To read a file’s contents, call f.read(size)

When size is omitted or negative, the entire contents of the file will be read and returned;

And the most relevant part:

If the end of the file has been reached, f.read() will return an empty string ('').

Which means that if you use read() twice consecutively, it is expected that the second time you'll get an empty string. Either store it the first time or use f.seek(0) to go back to the start. Together, they provide a lower level API to give you greater control.

Besides using a context manager to automatically open and close the file, there's another way to read a whole text file, using pathlib, example below:

#!/usr/bin/env python3

from pathlib import Path


txt_file = Path("myfile.txt")

try:
    content = txt_file.read_text()
except FileNotFoundError:
    print("Could not find file")
else:
    print(f"The content is: {content}")
    print(f"I can also read again: {txt_file.read_text()}")

As you can see, you can call read_text() several times and you'll get the full content, no surprises. Of course you wouldn't want to do that in production code since read_text() opens and closes the file each time, it's still best to store it. I could recommend pathlib highly when dealing with files and file paths.

It's outside the scope, but it may be worth noting a difference when reading line by line. Unlike the file object obtained by open(), PosixPath returned by Path() is not iterable. The equivalent of:

with open('file.txt') as f:
    for line in f:
        print(line)

Would be something like:

for line in Path('file.txt').read_text().split('\n'):
    print(line)

One advantage of the first approach, with open, is that the entire file is not read into memory at once.


make sure your location is correct. Do you actually have a directory called /council under your root directory (/) ?. also use, os.path.join() to create your path

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜