FileNotFoundError: [WinError 2] 系统找不到指定的文件:在os.listdir中查找扩展名
我想在一个指定的文件夹里删除所有文件,只留一个。看过其他相关的帖子,但我这个问题似乎是关于如何从os.listdir获取文件名,并且需要完整路径和扩展名来使用os.remove:
# delete files from the save path but preserve the zip file
if os.path.isfile(zip_path):
for clean_up in os.listdir(data_path):
if not clean_up.endswith(tStamp+'.zip'):
os.remove(clean_up)
出现了这个错误:
Line 5: os.remove(clean_up)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'firstFileInListName'
我觉得这是因为os.listdir没有获取到每个文件的扩展名(我打印了os.listdir(data_path),结果只得到了文件名,没有扩展名)
我该怎么做才能删除data_path里的所有文件,除了那个以tStamp+'.zip'结尾的文件呢?
1 个回答
1
如果你不一定要使用 os
模块,我建议你用 pathlib
里的 Path
类。个人觉得它更容易读懂,用起来也不那么笨重。
from pathlib import Path
# assuming zip_path = Path("path/to/zip_file_you_dont_want_to_delete.zip")
zip_path_parent = zip_path.parent
# delete files from the save path but preserve the zip file
for file in zip_path_parent.glob("*.*"):
if file.is_file():
if file.suffix != ".zip":
file.unlink()
它有几个方法非常实用,可以帮助你替换路径的某些部分,或者获取路径的组成部分,比如:
file.stem
-> 输出 "some_file.some_extension"file.suffix
-> 输出 ".some_extension"file.name
-> 输出 "some_file"file.with_stem('some_new_file_name')
-> 输出 "some_new_file_name.some_extension"file.with_suffix('.txt')
-> 输出 "some_file.txt"file.with_name("new_file.txt")
-> 输出 "some/path/new_file.txt"