开发者

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.


  1. Open the file
  2. Check the size
  3. 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜