如何迭代给定目录中的文件?
- 2024-12-03 08:45:00
- admin 原创
- 150
问题描述:
我需要遍历给.asm
定目录内的所有文件并对它们执行一些操作。
如何才能有效地做到这一点?
解决方案 1:
上述答案的 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
或者以递归方式使用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)
用来
rglob
替换glob('**/*.asm')
rglob('*.asm')
这就像在给定的相对模式前面添加调用
Path.glob()
一样:'**/'
from pathlib import Path
pathlist = Path(directory_in_str).rglob('*.asm')
for path in pathlist:
# because path is object not string
path_in_str = str(path)
# print(path_in_str)
原始答案:
import os
for filename in os.listdir("/path/to/dir/"):
if filename.endswith(".asm") or filename.endswith(".py"):
# print(os.path.join(directory, filename))
continue
else:
continue
解决方案 2:
这将遍历所有后代文件,而不仅仅是目录的直属子文件:
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)
解决方案 3:
您可以尝试使用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 使用的规则查找与指定模式匹配的所有路径名,尽管返回的结果顺序是任意的。没有进行波浪符号扩展,但 *、? 和用 [] 表示的字符范围将正确匹配。
解决方案 4:
从 Python 3.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 上只需要对符号链接进行系统调用。
解决方案 5:
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
这些技术都不能保证任何迭代顺序
是的,非常难以预测。请注意,我对文件名进行了排序,如果文件的顺序很重要,例如对于视频帧或时间相关的数据收集,这一点很重要。不过,一定要在文件名中添加索引!
解决方案 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)
要获取数组中所有目录的列表,可以使用os:
os.listdir(directory)
解决方案 8:
我对这个实现还不太满意,我希望有一个自定义构造函数,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)
解决方案 9:
我非常喜欢使用库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.")
解决方案 10:
我不明白为什么有些答案很复杂。这是我使用 Python 2.7 的方法。替换DIRECTORY_TO_LOOP
为您要使用的目录。
import os
DIRECTORY_TO_LOOP = '/var/www/files/'
for root, dirs, files in os.walk(DIRECTORY_TO_LOOP, topdown=False):
for name in files:
print(os.path.join(root, name))
解决方案 11:
通过这样做获取目录中的所有.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