如何遍历给定目录中的文件? [英] How can I iterate over files in a given directory?
本文介绍了如何遍历给定目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要遍历给定目录中的所有 .asm
文件并对它们执行一些操作.
I need to iterate through all .asm
files inside a given directory and do some actions on them.
如何有效地做到这一点?
How can this be done in a efficient way?
推荐答案
上述答案的 Python 3.6 版本,使用 os
- 假设您将目录路径作为 str
对象放在名为 directory_in_str
的变量中:
Python 3.6 version of the above answer, using os
- assuming that you have the directory path as a str
object in a variable called directory_in_str
:
import os
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".asm") or filename.endswith(".py"):
# print(os.path.join(directory, filename))
continue
else:
continue
或者递归地使用pathlib
:
Or recursively, using pathlib
:
from pathlib import Path
pathlist = Path(directory_in_str).glob('**/*.asm')
for path in pathlist:
# because path is object not string
path_in_str = str(path)
# print(path_in_str)
- 使用
rglob
将glob('**/*.asm')
替换为rglob('*.asm')
- 这就像调用
Path.glob()
在给定的相对模式前添加'**/'
:
from pathlib import Path pathlist = Path(directory_in_str).rglob('*.asm') for path in pathlist: # because path is object not string path_in_str = str(path) # print(path_in_str)
原答案:
Original answer:
import os for filename in os.listdir("/path/to/dir/"): if filename.endswith(".asm") or filename.endswith(".py"): # print(os.path.join(directory, filename)) continue else: continue
这篇关于如何遍历给定目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 这就像调用
查看全文