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.path.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!")