web-dev-qa-db-ja.com

ファイルが空かどうか調べる方法は?

テキストファイルがあります。
空かどうかを確認するにはどうすればよいですか。

213
webminal.org
>>> import os
>>> os.stat("file").st_size == 0
True
269
ghostdog74
import os    
os.path.getsize(fullpathhere) > 0
101
Jon

ファイルが存在しない場合、getsize()stat()の両方が例外をスローします。この関数は、スローせずにTrue/Falseを返します。

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
64
ronedg

何らかの理由ですでにファイルを開いている場合は、これを試すことができます。

>>> 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
22
robert king

わかりましたので、私は ghostdog74's answer とコメントを合わせてお楽しみください。

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

Falseは空でないファイルを意味します。

それでは、関数を書きましょう。

import os

def file_is_empty(path):
    return os.stat(path).st_size==0
9
Ron Klein

ファイルオブジェクトがあれば、

>>> 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
1
Qlimax

pathlibname__でPython3を使用している場合は、 statNAME _ メソッドを使用して os.stat() 情報にアクセスできます。このメソッドの属性はst_size(ファイルサイズはバイト):

>>> from pathlib import Path 
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
0
M.T