我需要遍历.asm给定目录中的所有文件并对它们执行一些操作。
.asm
如何以有效的方式做到这一点?
上述答案的 Python 3.6 版本,使用os- 假设您将目录路径作为一个str名为的变量中的对象directory_in_str:
os
str
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:
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')
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)
原答案:
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