python实现将某类文件复制到特定的目录下

最近在学习python,用python做了个文件搬动的实现

#coding:utf-8
#-*-codding:cp936-*-
import os
import fnmatch
import shutil
import time
#.decode('utf-8').encode('gbk')是为了让raw_input中显示中文
file_suffix=raw_input("输入文件后缀,例如*.txt:".decode('utf-8').encode('gbk'))
source_file=raw_input("输入源文件目录:".decode('utf-8').encode('gbk'))
target_file=raw_input("输入目标文件目录:".decode('utf-8').encode('gbk'))
if os.path.exists(target_file) == False:
    print 'The directory is not exist, It had make a new %s' % target_file
    os.makedirs(target_file)
    record="record.txt"
    file_record=os.path.join(target_file,record)
    f_handle=open(file_record,'a')

#利用os.walk遍历该文件目录下所有的目录和文件,通过os.path.join(rt,f)得到目标文件的路径,rt是起始路径,dirs是起始路径下的文件夹(列表),files是起始路径下的文件(列表)
def copy_file_to_targetDir(source_file):
    file_num=0
    for rt,dirs,files in os.walk(source_file):
        for f in files:
            if fnmatch.fnmatch(f,file_suffix):
                file_dir=os.path.join(rt,f)
                f_handle.write(file_dir + '\n')
                file_num+=1
                print file_dir
                shutil.copy(file_dir,target_file)
    print "\nIt totally find %d matched files" % file_num
    print "\nAll the file directory had been saved in record.txt"
    time.sleep(3)

copy_file_to_targetDir(source_file)
f_handle.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿玩AI

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值