python判断一个文件是否为空文件的几种方法

一. 思路分析

思路1: 获取文件大小, 验证文件大小是否为0(可以使用os库或pathlib库)

思路2: 读取文件的第一个字符, 验证第一个字符是否存在

二. 实现方法

方法1: 思路1 + os库的path方法

# -*- coding: utf-8 -*-
# @Time    : 2020/11/23 12:21
# @Author  : chinablue

import os


def is_empty_file_1(file_path: str):
    assert isinstance(file_path, str), f"file_path参数类型不是字符串类型: {type(file_path)}"
    assert os.path.isfile(file_path), f"file_path不是一个文件: {file_path}"
return os.path.getsize(file_path) == 0

方法2: 思路1 + os库的stat方法

# -*- coding: utf-8 -*-
# @Time    : 2020/11/23 12:21
# @Author  : chinablue

import os


def is_empty_file_2(file_path: str):
    assert isinstance(file_path, str), f"file_path参数类型不是字符串类型: {type(file_path)}"
    assert os.path.isfile(file_path), f"file_path不是一个文件: {file_path}"

    return os.stat(file_path).st_size == 0

方法3: 思路1 + pathlib库

# -*- coding: utf-8 -*-
# @Time    : 2020/11/23 12:21
# @Author  : chinablue

import pathlib


def is_empty_file_3(file_path: str):
    assert isinstance(file_path, str), f"file_path参数类型不是字符串类型: {type(file_path)}"
    p = pathlib.Path(file_path)
    assert p.is_file(), f"file_path不是一个文件: {file_path}"

    return p.stat().st_size == 0

方法4: 思路2

# -*- coding: utf-8 -*-
# @Time    : 2020/11/23 12:21
# @Author  : chinablue

import os


def is_empty_file_4(file_path: str):
    assert isinstance(file_path, str), f"file_path参数类型不是字符串类型: {type(file_path)}"
    assert os.path.isfile(file_path), f"file_path不是一个文件: {file_path}"

    with open(file_path, "r", encoding="utf-8") as f:
        first_char = f.read(1)
        if not first_char:
            return True
return False
原文地址:https://www.cnblogs.com/reconova-56/p/14204427.html