Python常用資料夾操作
阿新 • • 發佈:2018-12-18
- 匯入os庫
import os
- 檢測某路徑是否存在
if not os.path.exists(path):
- 建立某路徑
os.makedirs(path)
- 路徑拼接
os.path.join(path,file)
- 獲取某路徑下的資料夾和檔案
for file in os.listdir(path):
print(os.path.join(path,file))
- 遍歷資料夾下的所有資料夾/所有檔案,包括所有子目錄
path = r'C:/Users/LKP/Desktop\1'
for Parent, Dirnames, Filenames in os.walk(path):
for Dirname in Dirnames: # 遍歷所有資料夾
print(os.path.join(Parent,Dirname))
for Filename in Filenames: # 遍歷所有檔案
print(os.path.join(Parent,Filename))
Python路徑中斜槓的問題:在python3中,路徑不用擔心斜杆正反的煩惱,但是反斜槓要加\去除特殊轉義作用,或者加r’’