问题:如何检查文件是否为空?

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

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


回答 0

>>> import os
>>> os.stat("file").st_size == 0
True
>>> import os
>>> os.stat("file").st_size == 0
True

回答 1

import os    
os.path.getsize(fullpathhere) > 0
import os    
os.path.getsize(fullpathhere) > 0

回答 2

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

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

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

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

回答 3

如果由于某种原因您已经打开了文件,则可以尝试以下操作:

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

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

回答 4

好吧,我将把ghostdog74的答案和评论结合起来,只是为了好玩。

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

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

如果您将Python3与一起使用,则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

If you are using Python3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size(file size in bytes):

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

回答 6

如果您有文件对象,那么

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

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

回答 7

一个重要的陷阱:使用或函数测试时,压缩的空文件将显示为非零: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

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

An important gotcha: a compressed empty file will appear to be non-zero when tested with getsize() or stat() functions:

$ 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

So you should check whether the file to be tested is compressed (e.g. examine the filename suffix) and if so, either bail or uncompress it to a temporary location, test the uncompressed file, and then delete it when done.


回答 8

由于您尚未定义什么是空文件。有些人可能会认为只有空白行的文件也是空文件。因此,如果要检查文件是否仅包含空白行(任何空白字符,’\ r’,’\ n’,’\ t’),则可以按照以下示例进行操作:

Python3

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])
*量词-尽可能在零和无限次数之间进行匹配,并根据需要返回(贪婪)
$在行尾声明位置

Since you have not defined what an empty file is. Some might consider a file with just blank lines also an empty file. So if you want to check if your file contains only blank lines (any whitespace character, ‘\r’, ‘\n’, ‘\t’), you can follow the example below:

Python3

import re

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

Explain: the example above uses regular expression (regex) to match the content (content) of the file.
Specifically: for regex of: ^\s*$ as a whole means if the file contains only blank lines and/or blank spaces.
^ asserts position at start of a line
\s matches any whitespace character (equal to [\r\n\t\f\v ])
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line


回答 9

如果要检查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()

if you want to check csv file is empty or not …….try this

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。