【Python实用脚本】递归遍历复杂文件夹

229 阅读1分钟

应用场景

  1. 批量修改文件名
  2. 批量将文件导入数据库
  3. 其他应用场景 特点:无视文件夹结构,可以完整遍历复杂文件夹下的文件

代码案例

1. 修改文件名

import os

def recurse(base_path):
    if os.path.isdir(base_path):
        for file in os.listdir(base_path):
            child_path = os.path.join(base_path, file)
            # 如果是文件夹,则继续进入该文件夹
            if os.path.isdir(child_path):
                recurse(child_path)
            # 如果是文件,采取需要的操作(此处是修改文件名的例子)
            else:
                old_filename = child_path
                new_filename = 'what you need'
                os.rename(old_filename, new_filename)
                # 输出当前文件名(查看进度)
                print(child_path)


if __name__ == "__main__":

    path = 'C:\\Users\\Administrator\\Desktops\\filepath'
    recurse(path)

2. 读取csv并写入数据库

import os
import pandas as pd
from sqlalchemy import create_engine

def recurse(base_path, username, password, host, database, table):
    if os.path.isdir(base_path):
        for file in os.listdir(base_path):
            child_path = os.path.join(base_path, file)
            # 如果是文件夹,则继续进入该文件夹
            if os.path.isdir(child_path):
                recurse(child_path, username, password, host, database, table)
            # 如果是文件,采取需要的操作(此处是写入数据库的例子)
            else:
                # 可通过if跳过部分文件
                if base_path.rsplit('\')[-1] == '20226':
                    # 读取csv文件
                    data = pd.read_csv(child_path)
                    # 创建数据库引擎
                    conn = create_engine('mysql+pymysql://' + username + ':' + password + '@' + host + '/' + database + '?charset=UTF8MB4')
                    # 写入数据库
                    data.to_sql(table, conn, if_exists='append', index=False)
                    # 输出当前文件名(查看进度)
                    print(child_path)


if __name__ == "__main__":

    path = 'C:\\Users\\Administrator\\Desktops'
    host = 'localhost'
    username = 'root'
    password = '123456'
    database = 'test_database'
    table = 'test_table'

    recurse(path, username, password, host, database, table)

PS:总结分享学习心得,期待共同进步,望不吝批评指教!
PS2:算是第一次写博客,是太简单了点,还会继续提高质量!