python的幾種copy方法


1、os.system

import os

filename1 = r'G:\test\a'
filename2 = r'G:\test\test\a'
os.system('copy %s %s' % (filename1, filename2))  # 拷文件
if os.path.isfile(filename2): print 'copy file success'

dirname1 = r'G:\test\test'
dirname2 = r'G:\test\bbc'
# 將test目錄下的文件和非空目錄拷貝到bbc下,bbc若不存在將失敗
os.system('xcopy %s %s /s' % (dirname1, dirname2))  # 拷目錄,/s 復制非空的目錄和子目錄。
if os.path.isdir(dirname2): print 'copy dir success'

 

2、shutil.copy和shutil.copytree

import shutil

filename1 = r'G:\test\a'
filename2 = r'G:\test\test\a'
shutil.copy(filename1, filename2)  # 拷文件

dirname1 = r'G:\test\test'
dirname2 = r'G:\test\bbc'
shutil.copytree(dirname1, dirname2)  # 拷貝目錄,bbc若存在將報錯

 

3、win32File.CopyFile

需要安裝pywin32:http://jingyan.baidu.com/article/22fe7ced1ca36b3003617f7a.html

import win32file

filename1 = r'G:\test\a'
filename2 = r'G:\test\test\a'
# 拷文件
# 文件已存在時,1為不覆蓋,0為覆蓋
win32file.CopyFile(filename1, filename2, 0)  # 文件存在且為1時,會報錯

 

win32file.CopyFile (dirname1, dirname2, 1)

使用這種方法拷目錄沒有成功。。。

 

另外使用SHFileOperation的方法,

from win32com.shell import shell, shellcon導入沒有成功。。。不知道還要安裝什么

 

參考:http://www.cnblogs.com/lovemo1314/archive/2010/11/11/1874975.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM