在Python中检查文本文件是否为空,可以通过以下几种方法实现:
open()
,用于读取和写入文件。以下是几种检查文本文件是否为空的方法:
os.path.getsize()
import os
def is_file_empty(file_path):
return os.path.getsize(file_path) == 0
file_path = 'example.txt'
if is_file_empty(file_path):
print("文件为空")
else:
print("文件不为空")
def is_file_empty(file_path):
try:
with open(file_path, 'r') as file:
return not bool(file.read(1))
except FileNotFoundError:
print(f"文件 {file_path} 不存在")
return True
file_path = 'example.txt'
if is_file_empty(file_path):
print("文件为空")
else:
print("文件不为空")
def is_file_empty(file_path):
try:
with open(file_path, 'r') as file:
return not bool(file.readline())
except FileNotFoundError:
print(f"文件 {file_path} 不存在")
return True
file_path = 'example.txt'
if is_file_empty(file_path):
print("文件为空")
else:
print("文件不为空")
FileNotFoundError
。PermissionError
。open(file_path, 'r', encoding='utf-8')
。通过以上方法,可以有效地检查Python中的文本文件是否为空,并处理可能遇到的常见问题。
TVP技术夜未眠
《民航智见》线上会议
云+社区沙龙online第5期[架构演进]
原引擎 | 场景实战系列
云+社区技术沙龙[第6期]
腾讯云GAME-TECH沙龙
云+社区技术沙龙[第21期]
云+社区技术沙龙[第12期]
serverless days
领取专属 10元无门槛券
手把手带您无忧上云