-2

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')
Jakewae
  • 1
  • 5
  • The problem is in second parameter of open(). In current mode (r+) any new data writes over old data removing it. You must change 'r+' to 'a+' for open file in append data mode instead of rewriting. – StoneCountry May 02 '21 at 22:45

1 Answers1

1

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!
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50