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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM