How to check whether a file is empty or not?

2019-01-03 08:42发布

I have a text file.
How can I check whether it's empty or not?

6条回答
Explosion°爆炸
2楼-- · 2019-01-03 08:54

if for some reason you already had the file open you could try this:

>>> with open('New Text Document.txt') as my_file:
...     # I already have file open at this point.. now what?
...     my_file.seek(0) #ensure you're at the start of the file..
...     first_char = my_file.read(1) #get the first character
...     if not first_char:
...         print "file is empty" #first character is the empty string..
...     else:
...         my_file.seek(0) #first character wasn't empty, return to start of file.
...         #use file now
...
file is empty
查看更多
劫难
3楼-- · 2019-01-03 08:58

if you have the file object, then

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty
查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 09:03

Ok so I'll combine ghostdog74's answer and the comments, just for fun.

>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False

False means a non-empty file.

So let's write a function:

import os

def file_is_empty(path):
    return os.stat(path).st_size==0
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-03 09:13
import os    
os.path.getsize(fullpathhere) > 0
查看更多
家丑人穷心不美
6楼-- · 2019-01-03 09:18
>>> import os
>>> os.stat("file").st_size == 0
True
查看更多
姐就是有狂的资本
7楼-- · 2019-01-03 09:18

Both getsize() and stat() will throw an exception if the file does not exist. This function will return True/False without throwing:

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
查看更多
登录 后发表回答