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

2024-04-24 17:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何有效地做到这一点?


Tags: 文件目录asm
3条回答

这将遍历所有子代文件,而不仅仅是目录的直接子代:

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)

您可以尝试使用glob模块:

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)

由于Python3.5,您还可以搜索子目录:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

从文档中:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

原始答案:

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版本,使用^{}-假设在名为directory_in_str的变量中,目录路径是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

或者递归地使用^{}

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)

相关问题 更多 >