tags:

views:

75

answers:

3
myfile = open('out.txt', 'a')  
myfile.write(caption)

I write something like this whenever my script is run. But after the first run, it keeps on adding same data to the file. How can I check if it's empty or not and tell it to write only if it's empty?

+5  A: 

You could just check the file size of the target file with:

import os
b = os.path.getsize("path_to_file")
Hypnos
That introduces a race condition.
Philipp
+7  A: 

If you want clear out any existing data in the file first and write your output whether the file was empty or not, that's easy: just use

open('out.txt', 'w')

'w' means "write", 'a' means "append".

If you want to check whether the file has data in it and not write anything at all if there is data, then Hypnos' answer would be appropriate. Check the file size and skip the file-writing code if the file is not empty.

David Zaslavsky
+2  A: 

You can use file.read([size]) to check if a file is empty - if it returns None from the first time than is empty.

Give python doc a look.

Andrei T. Ursan