本文中Python代码实例为实现Python文件夹复制的效果。Python文件及文件夹拷贝(复制)、移动、删除、清空等操作使用方法讲解。编程之前要有思路,如文件操作前要判断文件或者目录是否存在,存在要如何处理,不存在文件或者目录又要如何处理。
Python文件夹复制方法代码正文部分如下:(供python学习朋友们参考)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#@author zcwang3@gmail.com
#@version 2010-09-25 14:57
import os
import time
sourceDir = r"\\192.168.3.250\mmtimages"
targetDir = r"D:\mmtimages"
copyFileCounts = 0
def copyFiles(sourceDir, targetDir):
global copyFileCounts
print sourceDir
print u"%s 此处为当前要处理文件夹%s已经处理%s多少个文件" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), sourceDir,copyFileCounts)
for f in os.listdir(sourceDir):
sourceF = os.path.join(sourceDir, f)
targetF = os.path.join(targetDir, f)
if os.path.isfile(sourceF):
#此处为创建目录
#www.iplaypy.com
if not os.path.exists(targetDir):
os.makedirs(targetDir)
copyFileCounts += 1
#文件不存在or存在,但是文件大小不同--覆盖
if not os.path.exists(targetF) or (os.path.exists(targetF) and (os.path.getsize(targetF) != os.path.getsize(sourceF))):
#2进制文件
open(targetF, "wb").write(open(sourceF, "rb").read())
print u"%s %s 复制完毕" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)
else:
print u"%s %s 文件已存在,不重复复制" %(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), targetF)
if os.path.isdir(sourceF):
copyFiles(sourceF, targetF)
if __name__ == "__main__":
try:
import psyco
psyco.profile()
except ImportError:
pass
copyFiles(sourceDir,targetDir)
本文仅为Python文件夹复制代码实例,Python文件夹复制代码编写及使用方法详解。想了解python文件及文件夹移动、删除、清空等其它操作方法,请关注玩蛇网相关文件操作代码文章。
推荐阅读相关内容:
Python open()函数文件打开、读、写write操作详解
玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/code/c2694.html
相关文章 Recommend