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

问题描述 投票:407回答:9

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

如何以有效的方式完成?

python iterator directory
9个回答
639
投票

原始答案:

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

使用os的上述答案的Python 3.6版本 - 假设您在名为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)

115
投票

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

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)

109
投票

您可以尝试使用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使用的规则查找与指定模式匹配的所有路径名,尽管结果以任意顺序返回。没有进行波浪线扩展,但*,?和用[]表示的字符范围将正确匹配。


14
投票

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)

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


6
投票

以下是我在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

没有这些技术保证任何迭代订购

是的,超级难以预料。请注意,我对文件名进行排序,如果文件的顺序很重要,即对于视频帧或时间相关的数据收集,这是很重要的。请确保将索引放在文件名中!


4
投票

我对这个实现不太满意,我想有一个自定义构造函数来执行DirectoryIndex._make(next(os.walk(input_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)

2
投票

从Python 3.5开始,使用os.scandir(可以轻松实现

with os.scandir(path) as it:
    for entry in it:
        if entry.name.endswith(".asm") and entry.is_file():
            print(entry.name, entry.path)

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


1
投票

您可以使用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)

0
投票

我真的很喜欢使用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.")
© www.soinside.com 2019 - 2024. All rights reserved.