python - 目录递归只深入一个目录
问题描述
我正在用 Python 编写一个脚本,以从编译内容中删除所有剩余的 .exe 文件:
import os
main_dir = '../RemoveExes'
def remove_all_in_dir(path):
print(f'Currently in {path}. Listdir:', os.listdir(path))
for current_name in os.listdir(path):
if os.path.isdir(current_name):
print(f'{path}/{current_name} is a directory. Entering')
remove_all_in_dir(f'{path}/{current_name}')
elif current_name.endswith('.exe'):
print(f'Would remove: {current_name}')
else:
print(f'{current_name} is not an .exe or a directory. Omitting.')
remove_all_in_dir(main_dir)
../RemoveExes 是一个具有以下结构的目录:
RemoveExes
├ bar
│ ├ subdir
│ │ ├ bulb.exe
│ │ └ some_text.txt
│ ├ doc.docs
│ └ een.jpg
├ foo
│ ├ exe.exe
│ └ txt.txt
├ cleanup.py
├ prog.exe
├ script.py
└ text.txt
该程序成功地“删除”了 exe.exe(1 个目录深)和 prog.exe(0 个目录深),但没有触及bulb.exe(2 个目录深)。这是为了限制 Python 中的递归,还是我做错了什么?
解决方案
os.listdir
仅返回文件名列表,不包含目录名,因此您应该将目录名与文件名连接起来以形成完整的路径名:
def remove_all_in_dir(path):
print(f'Currently in {path}. Listdir:', os.listdir(path))
for current_name in os.listdir(path):
full_path = os.path.join(path, current_name)
if os.path.isdir(full_path):
print(f'{full_path} is a directory. Entering')
remove_all_in_dir(f'{full_path}')
elif current_name.endswith('.exe'):
print(f'Would remove: {full_path}')
else:
print(f'{full_path} is not an .exe or a directory. Omitting.')
推荐阅读
- pdf - Apache Tika:解析的 PDF 包含矩形框 ,如何删除/解析这些字符?
- php - 为什么我的 PHP 准备好的语句没有插入到我的 MySQL 数据库中?
- ios - 为什么这个属性不能传递给这个函数?
- laravel - 未定义索引:id Laravel 5.8
- sql - SQL 返回 where IN 列表而不是任何其他值
- java - 在 IgniteRepository 中使用连接查询时无法从类型 [java.util.ArrayList ] 转换错误
- python - 有人可以解释一下这条线吗
- reactjs - 如何在useEffect hook中正确实现一个props回调函数
- selenium - 有没有一种简单的方法可以捕获 chrome 中包含 iframe 之外的元素的完整路径?
- java - 我正在使用 eclipse 并创建 BDD 框架。在我的跑步者文件中,Import cucumber.api is notsolved 如何解决这个问题?