前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >对数据进行按文件后缀名分类

对数据进行按文件后缀名分类

原创
作者头像
第4117座孤岛
发布2022-05-31 12:56:26
1K0
发布2022-05-31 12:56:26
举报
文章被收录于专栏:数据清洗数据清洗

from os import walk,getcwd,makedirs,system

from shutil import copyfile,rmtree

from os import path

代码语言:javascript
复制
cwd=getcwd()#获取当前路径
input(f"按下回车键将整理:{cwd}目录下的文件:")
d={}#保存各个类型的文件信息
cnt={}#保存重名文件的个数
idx={}#保存重名文件当前是几号,从1开始
if path.exists("output"):
rmtree("output")#删除之前的输出文件夹
for dirname,dirs,files in walk(cwd):
#遍历当前文件夹以及子文件夹下的所有文件
for i in files:
    #i表示文件名
    fileType=path.splitext(i)[1]#获取文件后缀名
    fileType=fileType.replace(".","")#替换后缀名的小数点
    if fileType.strip()=="":
        #没有后缀名的文件
        fileType="None"
    loction=dirname+"\\"+i#文件所在绝对路径
    baseName=path.split(loction)[1]#获取文件名,和i的值一样
    prefix=".".join(baseName.split(".")[0:-1])#获取文件前缀名
    if fileType=="None":
        prefix=baseName
    file={"fileType":fileType,"loction":loction,"baseName":baseName,"prefix":prefix}
    if fileType not in d.keys():
        d[fileType]=[file]
    else:
        d[fileType].append(file)
    if baseName not in cnt.keys():
        cnt[baseName]=1
        idx[baseName]=1
    else:
        cnt[baseName]+=1
#复制文件
for k,v in d.items():
#k表示文件类型
outputDir=f"output\\{k}"
if path.exists(outputDir) is False:
    #创建以文件类型(k)命名的文件夹
    makedirs(outputDir)
for file in v:
    #遍历改类型的所有文件
    newFilePath=outputDir+"\\"#储存该文件的新路径
    newBaseName=""
    if cnt[file["baseName"]]==1:
        #改文件只出现过一次
        newBaseName=file["baseName"]
    else:
        #该文件出现过多次需要使用下划线加编号格式保存
        newBaseName=file["prefix"]+"_"+str(idx[file["baseName"]])
        if file["fileType"]!="None":
            newBaseName=f"{newBaseName}.{file['fileType']}"
        idx[file["baseName"]]+=1
    newFilePath=cwd+"\\"+newFilePath+newBaseName
    copyfile(file["loction"],newFilePath)#复制文件
print("输出结果已保存到",cwd+"\output","文件夹中!")
system("pause")

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档