我需要遍历给定目录中的所有.asm文件,并对它们执行一些操作。
如何以有效的方式做到这一点?
我需要遍历给定目录中的所有.asm文件,并对它们执行一些操作。
如何以有效的方式做到这一点?
当前回答
自Python3.5以来,os.scandir()的操作变得更加简单,速度也快了2-20倍(来源):
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上的符号链接需要一个。
其他回答
下面是我如何在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
这些技术都不能保证任何迭代排序
是的,超级不可预测。请注意,我对文件名进行了排序,如果文件的顺序很重要,即对于视频帧或时间相关的数据收集,这一点很重要。不过,一定要在文件名中添加索引!
我非常喜欢使用内置在os库中的scandir指令。下面是一个工作示例:
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.")
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)
路径对象可以很容易地转换为字符串。
自Python3.5以来,os.scandir()的操作变得更加简单,速度也快了2-20倍(来源):
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上的符号链接需要一个。
通过执行此操作,获取目录中的所有.asm文件。
import os
path = "path_to_file"
file_type = '.asm'
for filename in os.listdir(path=path):
if filename.endswith(file_type):
print(filename)
print(f"{path}/{filename}")
# do something below