速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd
速戰速決 Python - python 標準庫: 目錄和文件管理
示例如下:
standardLib/os.py
# 通過 import os 實現目錄和文件管理
import os
# 刪除指定目錄下的目錄和文件(不包括指定目錄本身)
def deleteDir(path):
# topdown=False 的意思是從下往上遍歷(默認是從上往下遍歷)
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
# 刪除文件
os.remove(os.path.join(root, name))
for name in dirs:
# 刪除空目錄(如果目錄非空,則會拋出一個 OSError 異常)
os.rmdir(os.path.join(root, name))
path = r'd:\temp'
# 判斷路徑是否存在
if not os.path.exists(path):
# 創建目錄
os.mkdir(path)
# 創建目錄(如果當前目錄的父輩目錄們不存在,則自動創建它們)
os.makedirs(os.path.join(path, "dir1", "dir1_1"))
os.mkdir(os.path.join(path, "dir1", "dir1_2"))
os.mkdir(os.path.join(path, "dir1", "dir1_3"))
with open(os.path.join(path, "dir1", "dir1_1", "dir1_1_f1.txt"), 'w'): pass
with open(os.path.join(path, "dir1", "dir1_1", "dir1_1_f2.txt"), 'w'): pass
with open(os.path.join(path, "dir1", "dir1_1", "dir1_1_f3.txt"), 'w'): pass
os.makedirs(os.path.join(path, "dir2", "dir2_1"))
with open(os.path.join(path, "dir2", "dir2_1", "dir2_1_f1.txt"), 'w'): pass
# 刪除指定目錄下的目錄和文件(不包括指定目錄本身)
deleteDir(os.path.join(path, "dir2"))
# 判斷路徑是目錄還是文件
print(path + " isdir:", os.path.isdir(path)) # d:\temp isdir: True
print(path + " isfile:", os.path.isfile(path)) # d:\temp isfile: False
# 遍歷指定目錄下的目錄和文件
for home, dirs, files in os.walk(path):
print(home)
for dirName in dirs:
print("--" + dirName)
for fileName in files:
print("--" + fileName)
'''
上面語句的運行結果爲
d:\temp
--dir1
--dir2
d:\temp\dir1
--dir1_1
--dir1_2
--dir1_3
d:\temp\dir1\dir1_1
--dir1_1_f1.txt
--dir1_1_f2.txt
--dir1_1_f3.txt
d:\temp\dir1\dir1_2
d:\temp\dir1\dir1_3
d:\temp\dir2
'''
速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd