import os
# 文件路径
file_path = 'example.txt'
# 判断文件是否为空
if os.path.exists(file_path) and os.path.getsize(file_path) == 0:
# 删除空文件
os.remove(file_path)
print("文件已删除.")
else:
print("文件不为空或不存在.")
在上面的代码中,我们使用 os.path.exists(file_path)
来检查文件是否存在,同时使用 os.path.getsize(file_path)
来获取文件的大小。如果文件存在且大小为零,则表示文件为空。然后,我们使用 os.remove(file_path)
删除文件即可。
需要注意的是,确保指定的文件名和路径是正确的,以及有对文件的删除权限。