如何检查文件是否为空?

web*_*org 246 python file file-length

我有一个文本文件.
如何检查它是否为空?

gho*_*g74 309

>>> import os
>>> os.stat("file").st_size == 0
True
Run Code Online (Sandbox Code Playgroud)

  • @wRAR:os.stat('file').st_size甚至更好 (56认同)
  • `stat.ST_SIZE`而不是6 (10认同)
  • 也可以 但我不想导入统计信息。它短而甜美,返回列表中的大小位置不会很快改变。 (2认同)
  • 请注意,文件类型也适用于json。有时,用于空文件的json.load()不起作用,这提供了一种处理这种情况的好方法 (2认同)
  • @lone_coder 如果其中有换行符,它实际上不是空的。 (2认同)

Jon*_*Jon 111

import os    
os.path.getsize(fullpathhere) > 0
Run Code Online (Sandbox Code Playgroud)

  • 为了安全起见,您可能需要捕获`OSError`并返回False. (8认同)
  • 使用此vs os.state('file')有什么区别/优势.st_size? (4认同)
  • 看起来两者在引擎盖下是相同的:/sf/answers/1327358021/ (3认同)
  • @alper 20 是 gzip 压缩的空文件的大小。如果您的文件确实是空的,并且“ls -l”(或 Windows 上的“dir”)报告大小为 0,则“os.path.getsize()”也应该返回 0。 (3认同)

ron*_*edg 69

双方getsize()stat()会抛出一个异常,如果该文件不存在.此函数将返回True/False而不抛出:

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
Run Code Online (Sandbox Code Playgroud)

  • 存在竞争条件,因为在调用`os.path.isfile(fpath)`和`os.path.getsize(fpath)`之间可能会删除该文件,在这种情况下,建议的函数将引发异常. (6认同)
  • 最好尝试捕获`OSError`,就像提议[在另一个评论中](http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not/15924160#comment2503155_2507819 ). (2认同)

rob*_*ing 25

如果由于某种原因你已经打开文件你可以试试这个:

>>> 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
Run Code Online (Sandbox Code Playgroud)


M.T*_*M.T 18

如果您使用的是 Python 3,则pathlib可以os.stat()使用Path.stat()具有属性st_size(文件大小以字节为单位)的方法访问信息:

>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty
Run Code Online (Sandbox Code Playgroud)


Ron*_*ein 9

好的,所以我会把ghostdog74的答案和评论结合起来,只是为了好玩.

>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False
Run Code Online (Sandbox Code Playgroud)

False 表示非空文件.

那么让我们写一个函数:

import os

def file_is_empty(path):
    return os.stat(path).st_size==0
Run Code Online (Sandbox Code Playgroud)


Qli*_*max 9

如果你有文件对象,那么

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • 这个答案应该有更多的投票,因为它实际上检查文件是否有任何内容。 (2认同)