我需要遍历给定目录中的所有 .asm
文件并对它们执行一些操作。
如何以有效的方式做到这一点?
原文由 Itzik984 发布,翻译遵循 CC BY-SA 4.0 许可协议
这将遍历所有后代文件,而不仅仅是目录的直接子文件:
import os
for subdir, dirs, files in os.walk(rootdir):
for file in files:
#print os.path.join(subdir, file)
filepath = subdir + os.sep + file
if filepath.endswith(".asm"):
print (filepath)
原文由 pedromateo 发布,翻译遵循 CC BY-SA 3.0 许可协议
4 回答4.4k 阅读✓ 已解决
1 回答3.1k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.4k 阅读✓ 已解决
1 回答3.9k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
上述答案的 Python 3.6 版本,使用
os
- 假设您将目录路径作为str
对象在一个名为directory_in_str
的变量中或者递归地使用
pathlib
:rglob
将glob('**/*.asm')
替换为rglob('*.asm')
Path.glob()
与'**/'
在给定的相对模式前面添加:原答案: