gpt4 book ai didi

python - 目录递归只深入一个目录

转载 作者:行者123 更新时间:2023-12-04 10:31:15 25 4
gpt4 key购买 nike

我正在用 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.')

关于python - 目录递归只深入一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60418901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com