需求:一个文件夹下有相同文件名的两种格式的文件,且数量相等,我的两种文件格式是:jpg和tif.rbox.txt,想要把这两种文件分别放到两个文件夹里面
例如:将789文件夹下的两种文件分别放到456文件夹和000文件夹下(原来的456文件夹和000文件夹是空的)
代码如下:
# -*- coding: utf-8 -*-
import time
import os
import shutil
def readFilename(path, allfile):
filelist = os.listdir(path)
for filename in filelist:
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
readFilename(filepath, allfile)
else:
allfile.append(filepath)
return allfile
def mycopyfile(srcfile,dstfile):
if not os.path.isfile(srcfile):
print "%s not exist!"%(srcfile)
else:
fpath,fname=os.path.split(dstfile) #分离文件名和路径
if not os.path.exists(fpath):
os.makedirs(fpath) #创建路径
shutil.copyfile(srcfile,dstfile) #复制文件
print "copy %s -> %s"%( srcfile,dstfile)
if __name__ == '__main__':
path1="/Users/sunny/Desktop/789/"
path2="/Users/sunny/Desktop/456/"
path3="/Users/sunny/Desktop/000/"
allfile1=[]
allfile1=readFilename(path1,allfile1)
allname1=[]
for name in allfile1:
print name
t=name.split(".")[0].split("/")[-1]
print t
allname1.append(t)
print allname1
allname2=list(set(allname1))
print allname2
for ns in allname2:
srcfile=path1+str(ns)+'.jpg'
dstfile=path3+str(ns)+'.jpg'
mycopyfile(srcfile,dstfile)
srcfile=path1+str(ns)+'.tif.rbox.txt'
dstfile=path2+str(ns)+'.tif.rbox.txt'
mycopyfile(srcfile,dstfile)
运行结果如下: