我需要遍历给定目录中的所有.asm文件,并对它们执行一些操作。
如何以有效的方式做到这一点?
我需要遍历给定目录中的所有.asm文件,并对它们执行一些操作。
如何以有效的方式做到这一点?
当前回答
您可以使用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)
其他回答
我非常喜欢使用内置在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.")
这将遍历所有子代文件,而不仅仅是目录的直接子代:
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)
您可以使用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)
您可以尝试使用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使用的规则查找与指定模式匹配的所有路径名,尽管结果以任意顺序返回。未执行波浪号扩展,但*、?、?,并且用[]表示的字符范围将被正确匹配。
通过执行此操作,获取目录中的所有.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