我需要遍历.asm给定目录内的所有文件并对它们执行一些操作。
.asm
如何有效地做到这一点?
原始答案:
import os for filename in os.listdir(directory): if filename.endswith(".asm") or filename.endswith(".py"): # print(os.path.join(directory, filename)) continue else: continue
上面答案的Python 3.6版本,使用os-假设你将目录路径作为str对象包含在名为的变量中directory_in_str:
os
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)