Vangelis Tasoulas
Vangelis Tasoulas

Reputation: 3189

Python: How to know if a file I append text to, existed or just created?

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.

Upvotes: 7

Views: 1893

Answers (2)

shaktimaan
shaktimaan

Reputation: 12092

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

Upvotes: 8

AliBZ
AliBZ

Reputation: 4099

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?

Upvotes: 1

Related Questions