python批量移动文件_用python批量移动文件

我是用来移动图片的,其他格式的文档也是可以的,改下后缀列表就可以了

import os,shutil

import datetime

#将文件夹里的图片全部移动到新文件夹中

#revised by Stephen Shen 2020-3-10 09:28:50

def renameFile(dstpath):

fdirname,fbasename=os.path.split(dstpath)

#文件名相同但大小不同

fname,fext=os.path.splitext(fbasename)

nowtime=datetime.datetime.now()

strtime=str(nowtime.year)+str(nowtime.month)+str(nowtime.day)+str(nowtime.hour)+str(nowtime.minute)

newfbasename=fname+'-'+strtime+fext

dstpath=os.path.join(fdirname,newfbasename)

return dstpath

def moveFile(oldpath,newpath):

if os.path.exists(newpath):

newpath=renameFile(newpath)

try:

shutil.move(oldpath,newpath)

print(oldpath+' is moved')

except:

print(oldpath+' is skipped')

inpath=r'K:\fileExtracted\imagesFromDocs'

outpath=r'K:\filesExtracted'

image_ext=['.JPG','.jpg','.png','.PNG','.jpeg','.wdp']

image_outpath=os.path.join(outpath,'image')

doc_ext=['.doc','.docx']

doc_outpath=os.path.join(outpath,'doc')

emf_ext=['.emf']

emf_outpath=os.path.join(image_outpath,'emf')

wmf_ext=['.wmf']

wmf_outpath=os.path.join(image_outpath,'wmf')

if not os.path.exists(outpath):

os.makedirs(outpath)

if not os.path.exists(image_outpath):

os.makedirs(image_outpath)

if not os.path.exists(doc_outpath):

os.makedirs(doc_outpath)

if not os.path.exists(emf_outpath):

os.makedirs(emf_outpath)

if not os.path.exists(wmf_outpath):

os.makedirs(wmf_outpath)

for folder,subfolders,files in os.walk(inpath):

for file in files:

oldpath=os.path.join(folder,file)

if os.path.splitext(file)[-1] in image_ext:

newpath=os.path.join(image_outpath,file)

moveFile(oldpath,newpath)

elif os.path.splitext(file)[-1] in doc_ext:

newpath=os.path.join(doc_outpath,file)

moveFile(oldpath,newpath)

elif os.path.splitext(file)[-1] in emf_ext:

newpath=os.path.join(emf_outpath,file)

moveFile(oldpath,newpath)

elif os.path.splitext(file)[-1] in wmf_ext:

newpath=os.path.join(wmf_outpath,file)

moveFile(oldpath,newpath)

else:

continue

print('done')

然后再删除空文件夹

import os,shutil

#将文件夹里的空文件夹删除

#revised by Stephen Shen 2020-3-8 17:50:24

inpath=r'E:\pics-moving\待分类照片'

for folder,subfolders,files in os.walk(inpath):

if not os.listdir(folder):

shutil.rmtree(folder)

# print(folder+' is empyt')

print(folder+' is deleted')

print('done')

以上就是用python批量移动文件的详细内容,更多关于python批量移动文件的资料请关注我们其它相关文章!

本文标题: 用python批量移动文件

本文地址: http://www.cppcns.com/jiaoben/python/373766.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值