簡體   English   中英

無法在 python 中使用 os.remove() 從文件夾中刪除文件

[英]Unable to delete files from folder using os.remove() in python

我正在處理 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”的文件?

您需要指定要刪除的文件的目錄。 我會創建一個變量來保存文件路徑的字符串,如下所示:

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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM