python 檔案,資料夾,路徑操作

2022-02-01 18:03:11 字數 1214 閱讀 6154

判斷路徑或檔案

os.path.isabs(...)      # 判斷是否絕對路徑

os.path.exists(...)     # 判斷是否真實存在

os.path.isdir(...)     # 判斷是否是個目錄

os.path.isfile(...)     # 判斷是否是個檔案

路徑名、檔名分隔

os.path.split(...)    # 分隔目錄和檔名/資料夾名

os.path.splitdrive(...) # 分隔碟符(windows系統)

os.path.splitext(...) # 分隔檔案和副檔名

工作目錄及建立資料夾操作

os.getcwd()      # 獲取當前工作目錄

os.chdir(...)     # 改變工作目錄

os.listdir(...)     # 列出目錄下的檔案

os.mkdir(...)     # 建立單個目錄     注意:建立多級用 os.makedirs()

os.makedirs(...)   # 建立多級目錄

刪除資料夾/檔案

os.rmdir(...)         # 刪除空資料夾 注意:必須為空資料夾 如需刪除資料夾及其下所有檔案,需用 shutil

os.remove(...) # 刪除單一檔案

shutil.rmtree(...) # 刪除資料夾及其下所有檔案

重新命名資料夾/檔案

可對某一檔案或資料夾重新命名 os.rename(oldfilename, newfilename)

複製、移動資料夾/檔案

shutil.copyfile("old","new")      # 複製檔案,都只能是檔案

shutil.copytree("old","new")     # 複製資料夾,都只能是目錄,且new必須不存在

shutil.copy("old","new")     # 複製檔案/資料夾,複製 old 為 new(new是檔案,若不存在,即新建),複製 old 為至 new 資料夾(資料夾已存在)

shutil.move("old","new")      # 移動檔案/資料夾至 new 資料夾中

python檔案 資料夾操作

區別是glob列出的檔名包含了檔案路徑,即glob.glob括號內的路徑 而os.listdir只會獲取檔名。import glob file list glob.glob images 要列出所有內容路徑後面必須加 可以指定要遍歷的檔名格式 forfile in file list print f...

python資料夾操作

資料夾示意圖 提取路徑 size.py 提取相對路徑 import os print file 列印當前路徑 abspath os.getcwd 獲取當前路徑 ev os.path.abspath 獲取上一級目錄 rootpath os.path.abspath 獲取道根目錄的路徑 print ab...

python檔案和資料夾操作

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...