简体   繁体   中英

After writing to file f, calling f.read() returns None

The problem is that after writing to file it's empty, I dont understand why. here is my code:

    self.f = tempfile.NamedTemporaryFile(delete=False)    
    for i in range(self.num_chars_file):
        self.f.write(str(i))
    reader_writer.testfile = self.f.name
    print '************************'
    print self.f.read()

why does this happen, and how to correct this ?

You should move the file position to the beginning.

print '************************'
self.f.seek(0) # <--------
print self.f.read()

Otherwise, the file position is at the end of the file (where the file write was done)

You need to seek back to the start if you want to read the same data back again:

self.f.seek(0)
print self.f.read()

File objects are linear, like a tape, and have a 'current position'. When you write to a file, the current position moves along, so that new writes take place at that position, moving the position onwards again. The same applies to reading.

So, after writing, the file position is right at the end of the file. Trying to read without moving the file position means no more data will be found. file.seek() moves the current file position elsewhere; file.seek(0) moves it back to the start of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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