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

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


当前回答

您可以使用glob来引用目录和列表:

import glob
import os

#to get the current working directory name
cwd = os.getcwd()
#Load the images from images folder.
for f in glob.glob('images\*.jpg'):   
    dir_name = get_dir_name(f)
    image_file_name = dir_name + '.jpg'
    #To print the file name with path (path will be in string)
    print (image_file_name)

要获取数组中所有目录的列表,可以使用os:

os.listdir(directory)

其他回答

您可以尝试使用glob模块:

import glob

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

从Python 3.5开始,您还可以搜索子目录:

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

从文档中:

glob模块根据Unix shell使用的规则查找与指定模式匹配的所有路径名,尽管结果以任意顺序返回。未执行波浪号扩展,但*、?、?,并且用[]表示的字符范围将被正确匹配。

Python 3.4及更高版本在标准库中提供了pathlib。你可以这样做:

from pathlib import Path

asm_pths = [pth for pth in Path.cwd().iterdir()
            if pth.suffix == '.asm']

或者如果你不喜欢列表理解:

asm_paths = []
for pth in Path.cwd().iterdir():
    if pth.suffix == '.asm':
        asm_pths.append(pth)

路径对象可以很容易地转换为字符串。

我对这个实现还不太满意,我希望有一个自定义构造函数来实现DirectoryIndex_make(next(os.walk(inputpath))),这样您就可以传递文件列表所需的路径。欢迎编辑!

import collections
import os

DirectoryIndex = collections.namedtuple('DirectoryIndex', ['root', 'dirs', 'files'])

for file_name in DirectoryIndex(*next(os.walk('.'))).files:
    file_path = os.path.join(path, file_name)

下面是我如何在Python中迭代文件:

import os

path = 'the/name/of/your/path'

folder = os.fsencode(path)

filenames = []

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith( ('.jpeg', '.png', '.gif') ): # whatever file types you're using...
        filenames.append(filename)

filenames.sort() # now you have the filenames and can do something with them

这些技术都不能保证任何迭代排序

是的,超级不可预测。请注意,我对文件名进行了排序,如果文件的顺序很重要,即对于视频帧或时间相关的数据收集,这一点很重要。不过,一定要在文件名中添加索引!

您可以使用glob来引用目录和列表:

import glob
import os

#to get the current working directory name
cwd = os.getcwd()
#Load the images from images folder.
for f in glob.glob('images\*.jpg'):   
    dir_name = get_dir_name(f)
    image_file_name = dir_name + '.jpg'
    #To print the file name with path (path will be in string)
    print (image_file_name)

要获取数组中所有目录的列表,可以使用os:

os.listdir(directory)