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

Itz*_*984 477 python directory iterator

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

如何以有效的方式完成?

小智 708

原始答案:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

或递归,使用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)
Run Code Online (Sandbox Code Playgroud)

  • 如果您在2017年或之后看到这一点,os.scandir(dir_str)现在可用并且使用起来更干净.不需要fsencode.`for os.scandir(path)中的条目:print(entry.path)` (40认同)
  • `print(os.path.join(directory,filename))`需要更改为`print(os.path.join(directory_in_str,filename))`以使其在python 3.6中工作 (11认同)
  • 请注意,在Python 3.6中,目录应该是以字节为单位,然后listdir将以字节数据类型的形式列出文件名列表,因此您无法直接在其上运行endwith.对于os.listdir(目录)中的文件,此代码块应更改为`directory = os.fsencode(directory_in_str):filename = os.fsdecode(file)if filename.endswith(".asm")或filename.endswith(" .py"):#print(os.path.join(directory,filename))继续其他:继续` (7认同)
  • Python 3.7+:删除行directory = os.fsencode(directory_in_str),如下所述:/sf/ask/3411055511/成分 (4认同)
  • 优先于`if filename.endswith((“。asm”,“ .py”)):`而不是`if filename.endswith(“。asm”)或filename.endswith(“。py”):` (2认同)

ped*_*teo 127

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

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)
Run Code Online (Sandbox Code Playgroud)

  • os.walk函数的参考资料如下:https://docs.python.org/2/library/os.path.html#os.path.walk (3认同)

Dob*_*boy 117

您可以尝试使用glob模块

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)
Run Code Online (Sandbox Code Playgroud)


小智 17

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

from pathlib import Path

asm_pths = [pth for pth in Path.cwd().iterdir()
            if pth.suffix == '.asm']
Run Code Online (Sandbox Code Playgroud)

或者,如果您不喜欢列表推导:

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

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


Dan*_*ath 8

这是我遍历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
Run Code Online (Sandbox Code Playgroud)

这些技术均无法保证任何迭代顺序

是的,超级变幻莫测。请注意,我对文件名进行了排序,这在文件顺序很重要的情况下很重要,例如,对于视频帧或与时间有关的数据收集。不过,请务必在文件名中添加索引!


小智 7

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

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

os.listdir(directory)
Run Code Online (Sandbox Code Playgroud)


cry*_*ick 6

从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)
Run Code Online (Sandbox Code Playgroud)

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