【问题标题】:How to check whether a file is empty or not如何检查文件是否为空
【发布时间】:2026-02-20 11:05:01
【问题描述】:

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

【问题讨论】:

    标签: python file file-length


    【解决方案1】:
    >>> import os
    >>> os.stat("file").st_size == 0
    True
    

    【讨论】:

    • 这也很好。但我不想导入统计信息。它足够短而甜美,返回列表中的大小位置不会很快改变。
    • 请注意,文件类型也适用于 json。有时,空文件的 json.load() 不起作用,这提供了一种处理这种情况的好方法
    • 如果文件只包含新行/空怎么办?答案错误!
    • @lone_coder 如果里面有换行符,它实际上并不是空的。
    • @sappjw 但大小仍指示为零。这就是为什么这是错误的
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果文件不存在,getsize()stat() 都会抛出异常。此函数将返回 True/False 而不会抛出(更简单但不太健壮):

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

      【讨论】:

      • 绝对喜欢用os.path.getsize()
      • 存在竞争条件,因为在调用 os.path.isfile(fpath)os.path.getsize(fpath) 之间可能会删除文件,在这种情况下,建议的函数将引发异常。
      • 最好尝试抓住OSError,就像建议的in another comment一样。
      • 还需要捕获TypeError,如果输入fpath为None,则会引发。
      【解决方案4】:
      import os    
      os.path.getsize(fullpathhere) > 0
      

      【讨论】:

      • 为了安全起见,您可能需要捕获 OSError 并返回 False。
      • 使用 this 与 os.state('file').st_size 有什么区别/优势?
      • 看起来两者在底层是一样的:*.com/a/18962257/1397061
      • 即使文件为空也会返回 20
      • @alper 20 是压缩后的空文件的大小。如果您的文件确实是空的,ls -l(或 Windows 上的 dir)报告大小为 0,os.path.getsize() 也应该返回 0。
      【解决方案5】:

      如果你有文件对象,那么

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

      【讨论】:

      • 这个答案应该有更多的投票,因为它实际上检查文件是否有任何内容。
      【解决方案6】:

      一个重要的问题:使用getsize()stat() 函数测试时,压缩的空文件 将显示为非零:

      $ python
      >>> import os
      >>> os.path.getsize('empty-file.txt.gz')
      35
      >>> os.stat("empty-file.txt.gz").st_size == 0
      False
      
      $ gzip -cd empty-file.txt.gz | wc
      0 0 0
      

      因此,您应该检查要测试的文件是否已压缩(例如检查文件名后缀),如果是,请将其保释或解压缩到临时位置,测试未压缩的文件,然后在完成后将其删除。

      测试压缩文件大小的更好方法:使用the appropriate compression module 直接读取。您只需阅读文件的第一行 for example

      【讨论】:

      • 你在这里介绍的一个很好的陷阱!
      【解决方案7】:

      结合ghostdog74's answer 和 cmets:

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

      【讨论】:

        【解决方案8】:

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

        >>> 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" # The first character is the empty string..
        ...     else:
        ...         my_file.seek(0) # The first character wasn't empty. Return to the start of the file.
        ...         # Use file now
        ...
        file is empty
        

        【讨论】:

        • 正是我所拥有的场景......检查文件后,指针跳过了第一个字符,我对最终输出感到困惑......谢谢你......
        【解决方案9】:

        由于您尚未定义什么是空文件:有些人可能还会将只有空行的文件视为空文件。所以如果你想检查你的文件是否只包含空行(任何空白字符,'\r','\n','\t'),你可以按照下面的例子:

        Python 3

        import re
        
        def whitespace_only(file):
            content = open(file, 'r').read()
            if re.search(r'^\s*$', content):
                return True
        

        说明:上例使用正则表达式(regex)来匹配文件的内容(content)。

        特别是:对于 ^\s*$ 的正则表达式,作为一个整体意味着文件是否仅包含空行和/或空格。

        • ^ 在行首断言位置
        • \s 匹配任何空白字符(等于 [\r\n\t\f\v ])
        • * Quantifier — 匹配 0 次到无限次,尽可能多次,按需回馈(贪婪)
        • $ 在行尾断言位置

        【讨论】:

        • 我投了反对票,因为 1- 没有必要定义一个空文件:它是一个没有内容的文件。包含空行的文件不为空。 2- 这会读取内存中的整个文件。
        • 我认为这也是不好的答案。因为它只适用于真正的空白文件。但是一旦文件不是空白的,您可能会遇到许多错误,其中一个是UnicodeDecodeError。请谨慎使用此解决方案。
        【解决方案10】:

        如果您想检查 CSV 文件是否为空或 不,试试这个:

        with open('file.csv', 'a', newline='') as f:
            csv_writer = DictWriter(f, fieldnames = ['user_name', 'user_age', 'user_email', 'user_gender', 'user_type', 'user_check'])
            if os.stat('file.csv').st_size > 0:
                pass
            else:
                csv_writer.writeheader()
        

        【讨论】:

          【解决方案11】:

          将 JSON 附加到文件的完整示例

          可重用函数

          import json
          import os 
          
          def append_json_to_file(filename, new_data):
              """ If filename does not exist """
              data = []
              if not os.path.isfile(filename):
                  data.append(new_data)
                  with open(filename, 'w') as f:
                      f.write(json.dumps(data))
              else:
                  """ If filename exists but empty """
                  if os.stat(filename).st_size == 0:
                      data = []
                      with open(filename, 'w') as f:
                          f.write(json.dumps(data))
                  """ If filename exists """
                  with open(filename, 'r+') as f:
                      file_data = json.load(f)
                      file_data.append(new_data)
                      f.seek(0)
                      json.dump(file_data, f)
          

          运行它

          filename = './exceptions.json'
          append_json_to_file(filename, {
              'name': 'LVA',
              'age': 22
          })
          append_json_to_file(filename, {
              'name': 'CSD',
              'age': 20
          })        
          

          结果

          [{"name": "LVA", "age": 22}, {"name": "CSD", "age": 20}]
          

          【讨论】: