python文件屬性判斷(是否存在,是否爲空)

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章