繁体   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