【发布时间】: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