1. 程式人生 > >Python常用資料夾操作

Python常用資料夾操作

@[email protected]/?

  1. 匯入os庫
import os
  1. 檢測某路徑是否存在
if not os.path.exists(path):
  1. 建立某路徑
os.makedirs(path)
  1. 路徑拼接
os.path.join(path,file)
  1. 獲取某路徑下的資料夾和檔案
for file in os.listdir(path):
    print(os.path.join(path,file))
  1. 遍歷資料夾下的所有資料夾/所有檔案,包括所有子目錄
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’’

@[email protected]/?