001:os.system
import os, tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1,"w").close ()
filename2 = filename1 +".copy"
printfilename1,"=>", filename2 #拷文件
os.system ("copy %s %s"% (filename1, filename2))
ifos.path.isfile (filename2):print"Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 +".copy"
printdirname1,"=>", dirname2 #拷目录
os.system ("xcopy /s %s %s"% (dirname1, dirname2))
ifos.path.isdir (dirname2):print"Success"
2. shutil.copy和shutil.copytree
import os, shutil, tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1,"w").close ()
filename2 = filename1 +".copy"
printfilename1,"=>", filename2 #拷文件
shutil.copy (filename1, filename2)
ifos.path.isfile (filename2):print"Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 +".copy"
printdirname1,"=>", dirname2
#拷目录 复制文件夹及文件夹下面的所有文件 (比较重要)
shutil.copytree (dirname1, dirname2)
ifos.path.isdir (dirname2):print"Success"
3. win32file.CopyFile
import os, win32file, tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1,"w").close ()
filename2 = filename1 +".copy"
printfilename1,"=>", filename2
#拷文件 文件已存在时,1为不覆盖,0为覆盖
win32file.CopyFile (filename1, filename2,1)
win32file.CopyFile (filename1, filename2,0)
win32file.CopyFile (filename1, filename2,1)
if os.path.isfile (filename2):print"Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 +".copy"
print dirname1,"=>", dirname2 #拷目录
win32file.CopyFile (dirname1, dirname2,1)
ifos.path.isdir (dirname2):print"Success"
4. SHFileOperation
import os, tempfile
from win32com.shell import shell, shellcon
filename1 = tempfile.mktemp (".txt")
open (filename1,"w").close ()
filename2 = filename1 +".copy"
printfilename1,"=>", filename2
#拷文件 文件已存在时,shellcon.FOF_RENAMEONCOLLISION会指示重命名文件
shell.SHFileOperation ((0, shellcon.FO_COPY, filename1, filename2,0,None,None))
shell.SHFileOperation ((0, shellcon.FO_COPY, filename1, filename2, shellcon.FOF_RENAMEONCOLLISION,None,None))
shell.SHFileOperation ((0, shellcon.FO_COPY, filename1, filename2,0,None,None))
ifos.path.isfile (filename2):print"Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 +".copy"
printdirname1,"=>", dirname2 #拷目录
shell.SHFileOperation ((0, shellcon.FO_COPY, dirname1, dirname2,0,None,None))
ifos.path.isdir (dirname2):print"Success"
测试环境:系统——Win7 RTM,CPU——P4 3.0,MEM——1.5G DDR400,U盘——Kingston 4G
用4种不同的方法从硬盘拷贝MSDN 2008 SP1(2.37G)到U盘:
os System 的方法耗时903.218秒
shutil 的方法耗时1850.634秒
win32file 的方法耗时861.438秒
SHFileOperation的方法耗时794.023秒
文章转自:http://bbs.csdn.net/topics/320025687