python复制文件操作实例详解

本文实例讲述了python复制文件操作用法。分享给大家供大家参考,具体如下:

这里用python实现了一个小型的自动发版本的工具。这个“自动发版本”有点虚, 只是简单地把debug 目录下的配置文件复制到指定目录,把release下的生成文件复制到同一指定,过滤掉不需要的文件夹(.svn),然后再往这个指定目录添加几个特定的文件。

这个是我的第一个python小程序。

下面就来看其代码的实现。

首先插入必要的库:

import os
import os.path
import shutil
import time, datetime

然后就是一大堆功能函数。第一个就是把某一目录下的所有文件复制到指定目录中:

def copyfiles(sourcedir, targetdir):
if sourcedir.find(“.svn”) > 0:
return
for file in os.listdir(sourcedir):
sourcefile = os.path.join(sourcedir, file)
targetfile = os.path.join(targetdir, file)
if os.path.isfile(sourcefile):
if not os.path.exists(targetdir):
os.makedirs(targetdir)
if not os.path.exists(targetfile) or(os.path.exists(targetfile) and (os.path.getsize(targetfile) != os.path.getsize(sourcefile))):
open(targetfile, “wb”).write(open(sourcefile, “rb”).read())
if os.path.isdir(sourcefile):
first_directory = false
copyfiles(sourcefile, targetfile)

删除一级目录下的所有文件:

def removefileinfirstdir(targetdir):
for file in os.listdir(targetdir):
targetfile = os.path.join(targetdir, file)
if os.path.isfile(targetfile):
os.remove(targetfile)

复制一级目录下的所有文件到指定目录:

def coverfiles(sourcedir, targetdir):
for file in os.listdir(sourcedir):
sourcefile = os.path.join(sourcedir, file)
targetfile = os.path.join(targetdir, file)
#cover the files
if os.path.isfile(sourcefile):
open(targetfile, “wb”).write(open(sourcefile, “rb”).read())

复制指定文件到目录:

def movefileto(sourcedir, targetdir):
shutil.copy(sourcedir, targetdir)

往指定目录写文本文件:

def writeversioninfo(targetdir):
open(targetdir, “wb”).write(“revison:”)

返回当前的日期,以便在创建指定目录的时候用:

def getcurtime():
nowtime = time.localtime()
year = str(nowtime.tm_year)
month = str(nowtime.tm_mon)
if len(month) < 2: month = '0' + month day = str(nowtime.tm_yday) if len(day) < 2: day = '0' + day return (year + '-' + month + '-' + day)

然后就是主函数的实现了:

if __name__ ==”__main__”:
print “start(s) or quilt(q) \n”
flag = true
while (flag):
answer = raw_input()
if ‘q’ == answer:
flag = false
elif ‘s’== answer :
formattime = getcurtime()
targetfoldername = “build ” + formattime + “-01″
target_file_path += targetfoldername
copyfiles(debug_file_path, target_file_path)
removefileinfirstdir(target_file_path)
coverfiles(release_file_path, target_file_path)
movefileto(firebird_file_path, target_file_path)
movefileto(assistantgui_file_path, target_file_path)
writeversioninfo(target_file_path+”\\readme.txt”)
print “all sucess”
else:
print “not the correct command”

希望本文所述对大家python程序设计有所帮助。

Posted in 未分类

发表评论