分享

python复制多层目录下的文件至其他盘符对应的目录中

 文炳春秋 2020-04-01

一、需求

app打包需要打入一些H5进去,以便更快的加载页面。这些H5文件是散落在各个文件夹中的【如下列所示】,偶尔各个文件夹还需新增文件,每次新增一个文件,需要改动jenkins上job脚本,比较麻烦,所以换一种思路来解决这个问题。

View Code

二、思路

让前端开发把需要打入app的H5文件放入D:\scripts\src目录上  --->  读取该目录下文件的绝对路径  --->  在workspace中寻找对应的文件 ---> 并将这些文件复制到新的目录中,进行7za打包

python代码如下:

 1 #!/usr/bin/env python3
 2 #-*- coding:GBK -*-
 3 # author by Michael Ho
 4 # contact:rui.he@geekthings.com.cn
 5 import os, shutil
 6 
 7 def copy_app_H5_file(x_root, x_dir, src_dir, dst_dir):
 8     if os.path.exists(dst_dir):
 9         shutil.rmtree(dst_dir)
10     for root, dirs, files in os.walk(x_root):
11         for d_name in dirs:
12             d_name = os.path.join(root, d_name).rstrip()
13             d_dir = d_name.replace(x_dir, dst_dir)
14             if not os.path.exists(d_dir):
15                 os.makedirs(d_dir)
16         for f_name in files:
17             f_name = os.path.join(root, f_name).rstrip()            
18             if(os.path.splitext(f_name)[1] == ".d"):
19                 s_file = f_name.replace(x_dir, src_dir)
20                 d_file = f_name.replace(x_dir, dst_dir)
21                 shutil.copyfile(s_file, d_file)
22                 # 判断复制是否成功
23                 if(s_file.replace(src_dir, "") == d_file.replace(dst_dir, "")):
24                     print(d_file + "->" + "拷贝成功")
25                 else:
26                     print("拷贝过程发生错误,请检查...")
27 
28 if __name__ == '__main__':
29     # 上传的小包根目录,默认是d:\scripts,不要去动它!!!
30     x_root = "d:\\scripts"
31     
32     # 小包目录,默认是src,需要把小包的文件放在一个叫src目录里面!!!
33     x_dir = "d:\\scripts\\src"
34     
35     # 从gitlab上获取的目录
36     src_dir = "d:\\Jenkins\\frontend_encrypt"
37 
38     # 需要复制到目标目录,一般对其目录进行打包
39     dst_dir = "d:\\Jenkins\\H5_APP"
40 
41     copy_app_H5_file(x_root, x_dir, src_dir, dst_dir)

三、说明

1.在Jenkins客户端在Windows上,python编码格式要设定成    # -*- coding:GBK -*-  (笔者当时写的是 # -*- coding: utf-8 -*-)不然Jenkins会报以下错误

SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xbf in position 0: invalid start byte

2.python调系统级的接口不算太友好,个人认为没有批处理方便。如果整个文件夹复制的话,还是 xcopy  src_dir dst_dir /s /e /f方便,所以Jenkins上打包的脚本,笔者为了打包速度,Windows打包机采用batch+python【以上个人见解、水平有限】

https://www.cnblogs.com/herui1991/p/12403814.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多