Reputation: 143
target=open("test.txt",'w+')
target.write('ffff')
print(target.read())
When running the following python script (test.txt is an empty file), it prints an empty string.
However, when reopening the file, it can read it just fine:
target=open("test.txt",'w+')
target.write('ffff')
target=open("test.txt",'r')
print(target.read())
This prints out 'ffff' as needed.
Why is this happening? Is 'target' still recognized as having no content, even though I updated it in line 2, and I have to reassign test.txt to it?
Upvotes: 3
Views: 1573
Reputation: 4770
Try flushing, then seeking the beginning of the file:
f = open(path, 'w+')
f.write('foo')
f.write('bar')
f.flush()
f.seek(0)
print(f.read())
Upvotes: 1
Reputation: 1121884
A file has a read/write position. Writing to the file puts that position at the end of the written text; reading starts from the same position.
Put that position back to the start with the seek
method:
with open("test.txt",'w+') as target:
target.write('ffff')
target.seek(0) # to the start again
print(target.read())
Demo:
>>> with open("test.txt",'w+') as target:
... target.write('ffff')
... target.seek(0) # to the start again
... print(target.read())
...
4
0
ffff
The numbers are the return values of target.write()
and target.seek()
; they are the number of characters written, and the new position.
Upvotes: 10
Reputation: 3361
No need to close and re-open it. You just need to seek back to the file's starting point before reading it:
with open("test.txt",'w+') as f:
f.write('ffff')
f.seek(0)
print(f.read())
Upvotes: 4