Home >Backend Development >Python Tutorial >Example sharing of recursively recording files with specified suffix names in Python
You only need to change three global variables and call directly:
# coding=utf-8 import os # 三个全局变量: root_folder = './root' # 将被递归的文件夹根目录 save_txt = './paths.txt' # 记录路径的文档 suffix_name = '.jpg' # 后缀名 # 递归记录指定后缀名的文件的绝对路径 def record(folder, save_txt): save_file = open(save_txt, 'a') for name in os.listdir(folder): if os.path.isdir(os.path.join(folder, name)): record(os.path.join(folder, name), save_txt) elif name.endswith(suffix_name): save_file.write('{}\n'.format(os.path.join(folder, name))) save_file.close() def main(): # 如果save_txt已存在,则删除 try: os.remove(save_txt) except OSError: pass # 开始递归记录 record(os.path.abspath(root_folder), save_txt) if __name__ == '__main__': main()
The above is the detailed content of Example sharing of recursively recording files with specified suffix names in Python. For more information, please follow other related articles on the PHP Chinese website!