python 复制文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 复制文件相关的知识,希望对你有一定的参考价值。
练习python,用python复制目录及文件,但是目录一多就出错,而且复制的也不全:
import os
import os.path
import time
dateFormat = time.strftime('%Y%m%d',time.localtime())
targetDir = 'C:/Users/Chaoaicai/Desktop/%s' % dateFormat
os.mkdir(targetDir)
sourceDir = 'D:/test'
try:
def copyFile(sourceDir, targetDir):
dirList = os.listdir(sourceDir)
for fileList in dirList:
os.chdir(sourceDir)
if os.path.isdir(fileList):
sourceDir = os.getcwd()+'/'+fileList
targetDir = targetDir+'/'+os.path.split(sourceDir)[1]
os.mkdir(targetDir)
copyFile(sourceDir, targetDir)
else:
open(targetDir+'/'+fileList,'wb').write(open(sourceDir+'/'+fileList,'rb').read())
except CopyFileError,error:
print ('copyFile error: %s' % error)
copyFile(sourceDir, targetDir)
用Python把某一目录下的文件复制到指定目录中,代码如下:
1、首先插入必要的库:
import osimport os.path
import shutil
import time, datetime
2、实现复制文件代码如下:
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)
3、主函数的实现:
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" 参考技术A
报错多半是这句 targetDir = targetDir+'/'+os.path.split(sourceDir)[1]
你这句把本来的targetDir覆盖了,导致后面的文件的目标文件夹被修改
发个我写的吧,参考下吧
def copyFile( sourceDir,targetDir ):if not os.path.exists( targetDir ):
os.makedirs( targetDir )
for filename in os.listdir( sourceDir ):
path = os.path.join( sourceDir,filename )
if os.path.isdir( path ):
targetSubDir = os.path.join( targetDir,filename )
copyFile( path,targetSubDir )
else:
targetPath = os.path.join( targetDir,filename )
open( targetPath,'wb' ).write( open( path,'rb' ).read() )本回答被提问者采纳 参考技术B 学习自带库, 并学会如何查资料. 然后你就能发现Python是有函数用来实现这种功能
shutil.copytree(src, dst, symlinks=False, ignore=None) 参考技术C windows下你就不要自己用"/"了,还有,哪有这样递归的。。。
python 复制文件到其他路径
#!/usr/bin/env/python # -*- coding: utf-8 -*- # @Time : 2018/11/7 16:34 # @Author : ChenAdong # @Email : [email protected] import os import logging import shutil logging.basicConfig(level=logging.WARN) def txt_reader(_path): f = open(_path, "r") _type = "" for line in f.readlines(): if line.split("|")[0] == "tokentype": tem = line.split("|")[1] tem = tem.strip() # tem = int(tem) if tem == "1.0": _type = "admin" elif tem == "2.0": _type = "c" elif tem == "3.0": _type = "a" else: logging.warning("%s 未找到tokentype字段" % _path) logging.debug("%s %s" % (_path, _type)) f.close() return _path, _type def move_to(from_dir, to_dir): # tem = from_dir.spilt("/") # for _file in tem: # if os.path.isdir(_file): # pass # else: shutil.copyfile(from_dir, "./%s/%s" % (to_dir, from_dir)) if __name__ == "__main__": for i in os.listdir(os.getcwd()): try: if os.path.isfile(i): _path, _type = txt_reader(i) # to_dir = "./%s/%s" % (_type, _path) move_to(_path, _type) except shutil.Error: logging.warning("%s 文件被忽略" % _path)
以上是关于python 复制文件的主要内容,如果未能解决你的问题,请参考以下文章