Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python 目录复制 脚本

python 目录复制 脚本

作者头像
用户5760343
发布于 2022-05-13 03:13:25
发布于 2022-05-13 03:13:25
8260
举报
文章被收录于专栏:sktjsktj

""" ################################################################################ Usage: "python cpall.py dirFrom dirTo". Recursive copy of a directory tree. Works like a "cp -r dirFrom/* dirTo" Unix command, and assumes that dirFrom and dirTo are both directories. Was written to get around fatal error messages under Windows drag-and-drop copies (the first bad file ends the entire copy operation immediately), but also allows for coding more customized copy operations in Python. ################################################################################ """

import os, sys maxfileload = 1000000 blksize = 1024 * 500

def copyfile(pathFrom, pathTo, maxfileload=maxfileload): """ Copy one file pathFrom to pathTo, byte for byte; uses binary file modes to supress Unicde decode and endline transform """ if os.path.getsize(pathFrom) <= maxfileload: bytesFrom = open(pathFrom, 'rb').read() # read small file all at once open(pathTo, 'wb').write(bytesFrom) else: fileFrom = open(pathFrom, 'rb') # read big files in chunks fileTo = open(pathTo, 'wb') # need b mode for both while True: bytesFrom = fileFrom.read(blksize) # get one block, less at end if not bytesFrom: break # empty after last chunk fileTo.write(bytesFrom)

def copytree(dirFrom, dirTo, verbose=0): """ Copy contents of dirFrom and below to dirTo, return (files, dirs) counts; may need to use bytes for dirnames if undecodable on other platforms; may need to do more file type checking on Unix: skip links, fifos, etc. """ fcount = dcount = 0 for filename in os.listdir(dirFrom): # for files/dirs here pathFrom = os.path.join(dirFrom, filename) pathTo = os.path.join(dirTo, filename) # extend both paths if not os.path.isdir(pathFrom): # copy simple files try: if verbose > 1: print('copying', pathFrom, 'to', pathTo) copyfile(pathFrom, pathTo) fcount += 1 except: print('Error copying', pathFrom, 'to', pathTo, '--skipped') print(sys.exc_info()[0], sys.exc_info()[1]) else: if verbose: print('copying dir', pathFrom, 'to', pathTo) try: os.mkdir(pathTo) # make new subdir below = copytree(pathFrom, pathTo) # recur into subdirs fcount += below[0] # add subdir counts dcount += below[1] dcount += 1 except: print('Error creating', pathTo, '--skipped') print(sys.exc_info()[0], sys.exc_info()[1]) return (fcount, dcount)

def getargs(): """ Get and verify directory name arguments, returns default None on errors """ try: dirFrom, dirTo = sys.argv[1:] except: print('Usage error: cpall.py dirFrom dirTo') else: if not os.path.isdir(dirFrom): print('Error: dirFrom is not a directory') elif not os.path.exists(dirTo): os.mkdir(dirTo) print('Note: dirTo was created') return (dirFrom, dirTo) else: print('Warning: dirTo already exists') if hasattr(os.path, 'samefile'): same = os.path.samefile(dirFrom, dirTo) else: same = os.path.abspath(dirFrom) == os.path.abspath(dirTo) if same: print('Error: dirFrom same as dirTo') else: return (dirFrom, dirTo)

if name == 'main': import time dirstuple = getargs() if dirstuple: print('Copying...') start = time.clock() fcount, dcount = copytree(*dirstuple) print('Copied', fcount, 'files,', dcount, 'directories', end=' ') print('in', time.clock() - start, 'seconds')

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Python 之 shutil模块
copy2(src, dst):连同权限一起复制,相当于cp -p src dst
py3study
2020/01/08
5560
python 目录复制类 脚本
""" Use: "python ...\Tools\visitor_cpall.py fromDir toDir trace?" Like System\Filetools\cpall.py,
用户5760343
2022/05/13
5360
Python 模版(二)
拷贝状态的信息,包括:mode bits, atime, mtime, flags
py3study
2020/01/14
1.7K0
Python文件(夹)基本操作
1、判断文件(夹)是否存在。 os.path.exists(pathname) 2、判断路径名是否为文件。 os.path.isfile(pathname) 3、判断路径名是否为目录。 os.path.isdir(pathname) 4、创建文件。 os.mknod(filename)    # Windows下不可用 open(filename, "w")   # 记得要关闭 5、复制文件。 shutil.copyfile("oldfile", "newfile")   # oldfile和newf
py3study
2020/01/03
8290
python 查找文件脚本 search_all.py
""" ################################################################################ Use: "python ...\Tools\search_all.py dir string". Search all files at and below a named directory for a string; uses the os.walk interface, rather than doing a find.find to collect names first; similar to calling visitfile for each find.find result for "*" pattern; ################################################################################ """
用户5760343
2022/05/13
3760
自动同步2个目录python脚本
#!/usr/bin/python # -*- coding: utf8 -*- import os import sys import filecmp import re import shutil file_list = [] def recursive_dir(dir1):     """     递归当前目录的文件和子目录     :param dir1: 传参 需要递归的目录     :return: 当前目录下所有文件和目录     """     curDir = os.path.absp
py3study
2020/01/15
1.3K0
python 代码总行数统计 脚本
""" Count lines among all program source files in a tree named on the command line, and report totals grouped by file types (extension). A simple SLOC (source lines of code) metric: skip blank and comment lines if desired. """
用户5760343
2022/05/13
1.1K0
python 遍历目录类 脚本
""" #################################################################################### Test: "python ...\Tools\visitor.py dir testmask [string]". Uses classes and subclasses to wrap some of the details of os.walk call usage to walk and search; testmask is an integer bitmask with 1 bit per available self-test; see also: visitor_*/.py subclasses use cases; frameworks should generally use__X pseudo private names, but all names here are exported for use in subclasses and clients; redefine reset to support multiple independent walks that require subclass updates; #################################################################################### """
用户5760343
2022/05/13
6780
十行代码--用python写一个USB病毒
昨天在上厕所的时候突发奇想,当你把usb插进去的时候,能不能自动执行usb上的程序。查了一下,发现只有windows上可以,具体的大家也可以搜索(搜索关键词usb autorun)到。但是,如果我想,比如,当一个usb插入时,在后台自动把usb里的重要文件神不知鬼不觉地拷贝到本地或者上传到某个服务器,就需要特殊的软件辅助。
用户1564362
2019/10/24
1.4K0
python 查找文件、删除、搜索类 脚本
""" Use: "python ...\Tools\visitor_collect.py searchstring rootdir". CollectVisitor simply collects a list of all files containing a search string, for display or later processing (e.g., replacement, auto-editing); pass in a test filename extensions list to constructor to override the default in SearchVisitor; this is roughy like find+grep for text exts; """
用户5760343
2022/05/13
6170
使用Python复制某文件夹下子文件夹名为"数据"文件夹下的所有以"DD"开头的文件夹到桌面
前几天在Python最强王者群【魏哥】问了一个Python自动化办公处理的问题,这里拿出来给大家分享下。
Python进阶者
2023/09/02
4510
使用Python复制某文件夹下子文件夹名为"数据"文件夹下的所有以"DD"开头的文件夹到桌面
Python自动化运维2
描述:yaml配置文件与xml配置文件以及json配置文件的共同之处是在于方便理解与使用,是配置文件更加的简洁通俗易懂;
全栈工程师修炼指南
2022/09/28
4160
Python自动化运维2
python ftp工具类 上传、下载文件夹 封装类
-------------------------常用工具------------------------------------------------------------
用户5760343
2022/05/13
1.2K0
Python文件与目录-os模块和shutil模块详解
os模块和 shutil模块是Python处理文件/目录的主要方式。os模块提供了一种使用操作系统相关功能的便捷方式,shutil模块是一种高级的文件/目录操作工具。
唔仄lo咚锵
2021/09/14
6780
Python文件与目录-os模块和shutil模块详解
Python同步文件
最近在做Python开发,研究了技术大牛写的脚本,在他的脚本上做了优化。优化脚本已在做过测试还是挺好用的,如果你觉得不错就直接拿到生产用吧。
py3study
2020/01/06
1.1K0
python3基础:目录操作
os模块提供了统一的操作系统接口函数,python中对文件和文件夹的操作都要涉及到os和shutil模块,在使用前需要使用import引入,例如;
py3study
2020/01/09
1.3K0
树莓派3B+ 人脸识别(OpenCV)
首先,所有的方法都有类似的过积,即都使用了分好类的训练数据集(人脸数据库,每 个人都有很多样本)来进行“训练”,对图像或视频中检测到的人脸进行分析,并从两方面来确定:是否识别到目标,目标真正被识别到的置信度的度量,这也称为置信度评分。
全栈程序员站长
2022/09/12
9500
树莓派3B+ 人脸识别(OpenCV)
Python之模块介绍
os.makedirs('dirname1/dirname2')  可生成多层递归目录
py3study
2020/01/08
7100
python复制目录
 最近有个windows下批量更新文件的小需求,将一个目录下的所有文件覆盖到另一个目录下,首先想到shutil模块,shutil模块主要用于文件夹的操作。其中copytree用来对目录进行复制,但是比较遗憾的是,如果目标文件已经存在的话,该函数就会报错抛异常了,非常的不给力..后面就直接用os.system调用了xcopy命令,生产环境上一跑,大部分机器是正常,某些机器会报"无效的参数数量"错误,绕了一圈还是自己写了个简单的copy函数..
py3study
2020/01/13
2.1K0
Linux 下Python 脚本编写的"奇技淫巧"
常用来定义一个脚本的说明文档,一般我们写python脚本会通过if..else 的方式来提供一个脚本说明文档,python不支持switch。所有很麻烦,其实,我们可以通过argparse来编写说明文档。
山河已无恙
2023/01/30
1.7K0
相关推荐
Python 之 shutil模块
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档