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

551 Views Asked by At

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 ?

2

There are 2 best solutions below

3
On

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.

0
On

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)