我是靠谱客的博主 无语皮带,这篇文章主要介绍python文件属性判断(是否存在,是否为空),现在分享给大家,希望可以做个参考。

1. 判断文件是否为空

os.path.getsize()返回文件的字节数,如果为0,则代表空。

复制代码
1
2
3
4
5
import os file = "/home/abc/a.txt" if not os.path.getsize(file): os.remove(file)

2. 判断文件/文件夹是否存在

os.path.exists()方法用于检验文件/文件夹是否存在。

复制代码
1
2
3
4
5
6
7
8
9
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

 先判断文件是否存在,如果存在则判断是否为空:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
# 文件是否存在,以及是否为空 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文件属性判断(是否存在内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部