5

I want to append some text to a file if it exists, or create the file and append some additional text to it if it was just created. I know that I can append/create by using open("filename","a"), as this line of code will create the file if it doesn't exist. However, how can I know if the file existed or it was just created?

Eventually I want to achieve this:

with(open("filename","a")) as f:
    if filename existed before open
        # Append text
    else if filename was just created
        # Append some headers
        # Append text

I could achieve this by checking if the file exists first (os.path.isfile(filename)) and then act accordingly, but I am looking for a more elegant way.

Vangelis Tasoulas
  • 3,109
  • 3
  • 23
  • 36

2 Answers2

8

One way would be to use tell after opening the file. If it returns '0' it means there is no content in it.

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • 1
    Nice! Thank you. It works as expected, since append file mode puts the pointer at the end of the file. If it returns 0, it means that there is nothing in the file yet. – Vangelis Tasoulas Apr 02 '14 at 20:49
  • Nothing better than code. `f.tell()` will return 0 if the file was just created. – Anupam Jan 05 '20 at 16:22
1

First check if the file exists or not:

import os.path
os.path.isfile(file_path)

There are a few ways to do that: How do I check whether a file exists using Python?

Community
  • 1
  • 1
AliBZ
  • 4,039
  • 12
  • 45
  • 67