一. 思路分析
思路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