How can I check if a file is empty or not? and empty it before writing if not?
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?
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.
You could just check the file size of the target file with:
import os b = os.path.getsize("path_to_file")
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.
- Open the file
- Check the size
- Write if size > 0
By opening the file before the size is checked you avoid any race conditions.
import os
with open('out.txt', 'a') as myfile:
if os.path.getsize(myfile) == 0:
myfile.write(caption)
精彩评论