概述
1. 判断文件是否为空
os.path.getsize()返回文件的字节数,如果为0,则代表空。
import os
file = "/home/abc/a.txt"
if not os.path.getsize(file):
os.remove(file)
2. 判断文件/文件夹是否存在
os.path.exists()方法用于检验文件/文件夹是否存在。
import os
path = "/home/abc/test_dir"
file = "/home/abc/test_file"
if not os.path.exists(path):
os.makedirs(path)
if not os.path.exists(file):
pass
先判断文件是否存在,如果存在则判断是否为空:
# 文件是否存在,以及是否为空
file = "/home/abc/test_file.txt"
if os.path.exists(file):
print(file, " is exists!")
sz = os.path.getsize(file)
if not sz:
print(file, " is empty!")
else:
print(file, " is not empty, size is ", sz)
else:
print(file, " is not exists!")
最后
以上就是无语皮带为你收集整理的python文件属性判断(是否存在,是否为空)的全部内容,希望文章能够帮你解决python文件属性判断(是否存在,是否为空)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复