python 遍历目录,复制指定文件

本文介绍了一个Python脚本,该脚本使用os模块遍历指定目录中的所有子目录及文件,并利用win32file模块将符合特定条件的图片文件(即文件名中包含'_1'的部分)复制到另一指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明:

用os.walk遍历目录 返回3个值,(parent,dirs,files),其中parent为字符串,上一级目录路径。dirs为list,内容为当前所有目录,files为list,当前所有文件

用win32file.CopyFile复制文件,3个参数,(源,目的,1/0) 1不覆盖,0覆盖




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#encoding=utf-8
#author: skybug
#date: 2014-01-14
#function: 遍历图片目录,复制图片首页
import os,sys,getopt,win32file
def walkdir_cp(srcdir,dstdir):
    srcdir = os.path.abspath(srcdir)
    dstdir = os.path.abspath(dstdir)
    for parent,dirs,files in os.walk(srcdir):
        if os.path.isdir(parent.replace(srcdir,dstdir)) ==False:
            os.mkdir(parent.replace(srcdir,dstdir))   #创建目的路径目录
        for file in files:
            if file.split('.')[0].split('_')[1]=='1' :    #判断是否为全文首页                     
                = os.path.join(parent,file)
                = os.path.join(parent.replace(srcdir,dstdir),file)
                win32file.CopyFile(a,b,0)                   #拷贝
    print 'cp OK'
def mkdir(srcdir,dstdir):
    srcdir = os.path.abspath(srcdir)
    dstdir = os.path.abspath(dstdir)
    for parent,dirs,files in os.walk(srcdir):
    print 'mkdir ok'
def usage():
    print '--src=srcdir          srcdir\n'
    print '--dst=srcdir          dstdir\n'
    print '-h                    echo this info\n'
opts, args = getopt.getopt(sys.argv[1:], "h",["src=","dst="]) #解析输入参数
for op,value in opts:
    if op  == '--src':
        srcdir = value
    elif op == '--dst':
        dstdir = value
    elif op == '-h':
        usage()
        sys.exit()
    else:
        usage()
        sys.exit()
walkdir_cp(srcdir,dstdir)

执行 python walk_cp_firstfile.py  --src=源路径 --dst=目标路径




      本文转自天山三害 51CTO博客,原文链接:http://blog.51cto.com/skybug/1351711,如需转载请自行联系原作者




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值