python - python - 在给定的目录中,如何迭代文件?

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

如何以有效的方式做到这一点?

时间:

原始答案:


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



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)



这将迭代所有文件,而不仅仅是目录:


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



for filepath in glob.iglob('my_dir/*.asm'):


 print(filepath)



从Python 3.5开始,你也可以搜索子目录:


glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']



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对象可以轻松转换为字符串。

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



这些技术都不保证迭代顺序。

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)



从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)



...