[問題] 如何取得os.listdir()結果的絕對路徑

看板Python作者 (奔跑的蝸牛)時間13年前 (2010/11/10 00:20), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串1/2 (看更多)
#coding=utf8 import os, shutil # 如下所見, cache_folders 這個 list 的 element 皆為資料夾路徑. # 這些路徑的檔案分隔符號頗亂, 有些用/, 有些用\, 有些用//, 有些用\\, # 且多半有混用的情況 cache_folders = \ [ 'C:\\Documents and Settings\\user\\Local Settings\\Application Data\\Mozilla\\Firefox\\Profiles\\uxkeooir.lite\\Cache', 'C:\\Documents and Settings\\user/Local Settings/Application Data/K-Meleon\\aqu123v4.default\\Cache', u'C:\\Documents and Settings\\user/Local Settings/Temporary Internet Files/', ur'D:/測試檔 output 備份/', #...過多, 故省略 ] # 現在, 我想把cache_folders中的每個資料夾中的檔案通通刪掉: for folder in cache_folders: for f in os.listdir(folder): if(os.path.isfile(f)): # 檔案可能是file os.remove(f) else: # 也可能是directory shutil.rmtree(f) --- 但f畢竟不是檔案路徑 要先取得路徑才能刪除 我想過幾個方法: 1) 把 f 的路徑 append 在folder的路徑後面 for folder in cache_folders: for f in os.listdir(folder): folder = refine(folder) #refine是另外寫的函式, 目的是把folder改成以"/"結尾 f = folder + f if(os.path.isfile(f)): # 檔案可能是file os.remove(f) else: # 也可能是directory shutil.rmtree(f) 2) 移到folder路徑後再刪除底下的檔案 for folder in cache_folders: for f in os.listdir(folder): os.chdir(folder) if(os.path.isfile(f)): # 檔案可能是file os.remove(f) else: # 也可能是directory shutil.rmtree(f) 我想請教的是: a. 有沒有辦法透過Python內建函式直接取得某資料夾內所有檔案的絕對路徑? 我的意思大概是這樣: for folder in cache_folders for f in list_abspath(folder): #有list_abspath這種函式嗎? if(os.path.isfile(f)): # 檔案可能是file os.remove(f) else: # 也可能是directory shutil.rmtree(f) b. 除了上述幾種方法, 還有什麼推薦的刪檔案方法嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.32 ※ 編輯: Holocaust123 來自: 140.112.30.32 (11/10 01:00)

11/10 14:12, , 1F
我都改用用glob了
11/10 14:12, 1F
文章代碼(AID): #1CsNIzX5 (Python)
文章代碼(AID): #1CsNIzX5 (Python)