I am trying to check if a file exists.
import os.path
from os import path
if path.exists('file.txt'):
f = open('file.txt', 'r+')
f.write('Hello there!')
f.close()
else:
print('No file')
I am trying to check if a file exists.
import os.path
from os import path
if path.exists('file.txt'):
f = open('file.txt', 'r+')
f.write('Hello there!')
f.close()
else:
print('No file')
However when I print out the file the second time it only prints out the text that was already in the file
No, it does not, your second print will print nothing (or rather only an empty line).
When you read a file object with read()
you're moving to the end of the object. Same with write
. If you want to read the whole file again, you must change the position from where you are reading with seek(0)
to the first position in the file object.
I've changed your code slighty to make use of the with
syntax, that closes the file for you:
import os.path
from os import path
if path.exists('file.txt'):
with open('file.txt', 'r+') as f:
contents = f.read()
print(contents)
f.write('Hello there!')
f.seek(0) # <-- go back to position 0
new_content = f.read()
print(new_content)
else:
print('No file')
Assuming your file content initially is ABC\n
this will print:
ABC
ABC
Hello there!