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