python脚本——根据某文件夹下所有文件名实现文件的复制

当时写这个脚本的需求是:想要得到文件夹下有相同的文件名(不包括后缀名)的两个文件夹,即:根据第一个文件夹中的文件名(不包括后缀名),复制第二个文件夹中的同名文件(不包括后缀名)到新的文件夹中。

例如:我的第一个文件夹(名称为:123)内容如下:

第二个文件夹(名称为:456)内容如下:

目标是得到:第三个文件夹(名称为:789)内容如下:(第二个和第三个文件夹具有所有的同名文件)

实现的代码如下:

# -*- 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/123/"
    path2="/Users/sunny/Desktop/456/"
    path3="/Users/sunny/Desktop/789/"
    allfile1=[]
    allfile2=[]
	allfile1=readFilename(path1,allfile1)
    allfile2=readFilename(path2,allfile2)
    allname1=[]
    allname2=[]
    for name in allfile1:
        t=name.split("/")[-1][0:-4]
        print t
        allname1.append(t)
        print allname1
    for name in allfile2:
        t=name.split("/")[-1][0:-9]
        print t
        allname2.append(t)
        print allname2
    s1=[]
    for ff in allname1:
        f (ff not in allname2):
            s1.append(ff)
    print s1
    s2=[]
    for ff in allname1:
        if (ff in allname2):
            s2.append(ff)
    print s2
    for ns in s2:
        srcfile=path1+str(ns)+'.jpg'
        dstfile=path3+str(ns)+'.jpg'
        mycopyfile(srcfile,dstfile)

运行过程如下:

随手做个笔记,以备不时之需。

猜你喜欢

转载自blog.csdn.net/shichunxue/article/details/81572139