如何遍历给定目录中的文件?

新手上路,请多包涵

我需要遍历给定目录中的所有 .asm 文件并对它们执行一些操作。

如何以有效的方式做到这一点?

原文由 Itzik984 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 274
2 个回答

上述答案的 Python 3.6 版本,使用 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

 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)

  • 使用 rglobglob('**/*.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

原文由 anselm 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题