Python遍历文件夹中的文件并根据文件类型将文件分类储存

发布时间 2023-09-06 15:48:52作者: Victooor_swd

最近在写某串代码,其逻辑是从源文件夹中遍历各个子文件夹,将其中不同文件类型的文件分类提取出来各自使用,需要提取.txt、.png、.csv文件三种,为了实现这一功能,用os包来实现

import os

#准备文件路径
for n in range(0,12854):    #这里我的文件名是0-12854,如果文件名不是循环的话需要再os.walk一下获取子文件夹
    print('The No.{} coordinate is handling'.format(n))
    general_path='路径/{}'.format(n)
    try:
        general_file=os.walk(general_path)
    except FileNotFoundError:
        print("No.{} coordinate is missing".format(n))

#创建保存文件名称的列表
    img_names=[]
    lonlat_names=[]
    csv_names=[]

#将各文件的名字提取到列表中 
    for root, dirs, files in general_file:
        img_names[:] = [f for f in files if f.endswith(".png")]
        lonlat_names[:] = [g for g in files if g.endswith(".txt")]
        csv_names[:] = [h for h in files if h.endswith(".csv")]

#从列表中遍历某类型的文件
        for lonlat in lonlat_names:
            print(lonlat)