Example sharing of recursively recording files with specified suffix names in Python

黄舟
Release: 2017-10-07 11:40:25
Original
1380 people have browsed it

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template