Python 如何迭代给定目录中的文件?

Python 如何迭代给定目录中的文件?,python,iterator,directory,Python,Iterator,Directory,我需要遍历给定目录中的所有.asm文件,并对它们执行一些操作 如何以有效的方式完成此操作?原始答案: 导入操作系统 对于os.listdir(目录)中的文件名: 如果filename.endswith(“.asm”)或filename.endswith(“.py”): #打印(os.path.join(目录,文件名)) 持续 其他: 持续 上述答案的Python 3.6版本,使用-假设您在名为directory\u in_str的变量中将目录路径作为str对象: 导入操作系统 director

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

如何以有效的方式完成此操作?

原始答案:

导入操作系统
对于os.listdir(目录)中的文件名:
如果filename.endswith(“.asm”)或filename.endswith(“.py”):
#打印(os.path.join(目录,文件名))
持续
其他:
持续
上述答案的Python 3.6版本,使用-假设您在名为
directory\u in_str
的变量中将目录路径作为
str
对象:

导入操作系统
directory=os.fsencode(目录在目录中)
对于os.listdir(目录)中的文件:
filename=os.fsdecode(文件)
如果filename.endswith(“.asm”)或filename.endswith(“.py”):
#打印(os.path.join(目录,文件名))
持续
其他:
持续
或递归地使用:

从pathlib导入路径
pathlist=Path(目录在\u str.glob('***.asm'))
对于路径列表中的路径:
#因为路径是对象而不是字符串
path_in_str=str(路径)
#打印(路径\u在\u str中)
  • 用于将
    glob('***.asm')
    替换为
    rglob('***.asm')
    • 这类似于在给定的相对模式前面添加
      '**/'
      进行调用:
从pathlib导入路径
pathlist=Path(目录\u在\u str.rglob('*.asm'))
对于路径列表中的路径:
#因为路径是对象而不是字符串
path_in_str=str(路径)
#打印(路径\u在\u str中)
您可以尝试使用模块:

由于Python 3.5,您还可以搜索子目录:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']
从文档中:

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


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

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)

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

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)

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

我对这个实现还不是很满意,我想有一个自定义的构造函数来执行
DirectoryIndex.\u make(next(os.walk(input\u Path))
,这样你就可以传递你想要的文件列表的路径。欢迎编辑

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
这些技术都不能保证任何迭代顺序


是的,超级难以捉摸。请注意,我对文件名进行了排序,如果文件的顺序很重要,这一点很重要,例如,对于视频帧或时间相关的数据采集。但一定要在文件名中添加索引

自Python 3.5以来,使用()和2-20倍的速度()就容易多了:

使用scandir()而不是listdir()可以显著提高 还需要文件类型或文件属性的代码的性能 信息,因为os.DirEntry对象在 操作系统在扫描目录时提供此功能。全部的 DirEntry方法可以执行系统调用,但它是_dir()和 is_file()通常只需要对符号链接进行系统调用; os.DirEntry.stat()始终需要在Unix上进行系统调用,但仅限于 Windows上的符号链接需要一个


我非常喜欢使用
scandir
指令,该指令内置于
os
库中。以下是一个工作示例:

import os

i = 0
with os.scandir('/usr/local/bin') as root_dir:
    for path in root_dir:
        if path.is_file():
            i += 1
            print(f"Full path is: {path} and just the name is: {path.name}")
print(f"{i} files scanned successfully.")
可用于引用目录和列表:

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)
要获取阵列中所有目录的列表,可以使用:


这似乎只是列出了目录下的目录或文件。下面pedromateo给出的答案似乎是一个递归列表。请注意,在Python 3.6中,目录应以字节为单位,然后listdir将以字节数据类型列出文件名列表,因此您不能直接在其上运行endswith。对于os.listdir(目录)中的文件,此代码块应更改为
directory=os.fsencode(directory_in_str):filename=os.fsdecode(file),如果filename.endswith(“.asm”)或filename.endswith(.py”):#print(os.path.join(directory,filename))继续其他:继续
print(os.path.join(directory,filename))
需要更改为print(os.path.join(directory_in_str,filename))才能在python 3.6中工作如果您在2017年或以后看到这一点,os.scandir(dir_str)现在可用,而且使用起来更干净。不需要fsencode
对于os.scandir(path)中的条目:打印(entry.path)
首选
如果filename.endswith((.asm“,.py”):
如果filename.endswith(.asm”)或filename.endswith(.py”):
os.walk函数的引用位于以下位置:
entry
是一种类型,具有许多方便的方法,例如
entry.is\dir()
是_文件()
是_符号链接()
重复应答不总是排序…im1,im10,im11…,im2…其他有用的方法。
从pkg_资源导入解析版本
文件名。排序(key=parse_版本)
完成了。
import os

i = 0
with os.scandir('/usr/local/bin') as root_dir:
    for path in root_dir:
        if path.is_file():
            i += 1
            print(f"Full path is: {path} and just the name is: {path.name}")
print(f"{i} files scanned successfully.")
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.listdir(directory)