【问题标题】:Unable to delete files from folder using os.remove() in python无法在 python 中使用 os.remove() 从文件夹中删除文件
【发布时间】:2021-12-07 19:56:18
【问题描述】:

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

【问题讨论】:

  • print(file) 是你最好的线索。它打印了一个文件名,而不是文件名 plus 目录。您需要将目录添加到该名称。

标签: python file directory operating-system


【解决方案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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2017-12-17
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    相关资源
    最近更新 更多