我正在處理 python 中的檔案目錄,我想在其中洗掉包含特定字串的檔案,最終使用 os.remove(),但我無法讓它作業。我將在這里通過顯示我正在使用的代碼進一步詳細說明:
directory = 'source_folder'
for color in colors:
for size in sizes:
for speed in speeds:
source = os.listdir(os.path.join(directory, color, size, speed))
for file in source:
if "p_1" in file:
print(file)
這將列印出目錄中所有檔案名中包含字串摘錄“p_1”的檔案,這正是我所期望的。每個“for”嵌套都表示導航到我的目錄層次結構中的另一個檔案夾級別。
我想要做的是洗掉檔案名中不包含“p_1”的每個檔案。所以我試過:
directory = 'source_folder'
for color in colors:
for size in sizes:
for speed in speeds:
source = os.listdir(os.path.join(directory, color, size, speed))
for file in source:
if "p_1" not in file:
os.remove(file)
但這會回傳:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Name_of_one_of_the_files_I_want_to_delete'
我在這里看不出我的邏輯錯在哪里,因為我可以列印我想洗掉的檔案,但由于某種原因我無法洗掉它們。如何修復我的代碼以洗掉檔案名中包含字串摘錄“p_1”的檔案?
uj5u.com熱心網友回復:
您需要指定要洗掉的檔案的目錄。我會創建一個變數來保存檔案路徑的字串,如下所示:
directory = 'source_folder'
for color in colors:
for size in sizes:
for speed in speeds:
some_path = os.path.join(directory, color, size, speed)
source = os.listdir(some_path)
for file in source:
if "p_1" not in file:
os.remove("/".join(some_path,file))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334143.html
上一篇:在android11中下載pdf
下一篇:c語言文本檔案上的fseek()
