Press "Enter" to skip to content

python中文件的复制

文件的复制
file类中没有提供专门的文件复制函数,因此只能通过使用文件的读写函数来实现文件的复制。这里仅仅给出范例:

src = file("myfile.txt", "w+")
temp = ["hello world! \n"]
src.writelines(temp)
src.close()

src = file("myfile.txt", "r+")
des = file("myfile2.txt", "w+")
des.writelines(src.read())
src.close()
des.close()

使用shutil来实现文件的拷贝
shutil.copyfile(src, dst) #文件到文件的拷贝,其中dst必须是一个文件
shutil.copy(src, dst) #文件拷贝,src必须是一个文件,dst可以是一个文件或者目录
shutil.copy2(src, dst) #同上,但是拷贝的文件带着原有属性,类似于Linux系统里的cp -p命令
shutil.move(src, dst) #移动一个文件或者目录到指定的位置,src和dst都可以是文件或者目录
shutil.copytree(src, dst, symlinks=False, ignore=None) #目录的复制

import shutil

shutil.copyfile("myfile1.txt", "myfile2.txt")
shutil.move("myfile1.txt", "../") #把myfile1.txt移动到当前目录的父目录,然后删除myfile1.txt
shutil.move("myfile2.txt", "myfile3.txt") #把myfile2.txt移动到当前目录并重命名myfile3.txt
shutil.rmtree('c:\\test')  #删除整个文件夹(文件夹可以是非空的)

更详细的shutil命令可以参考http://docs.python.org/2/library/shutil.html

Leave a Reply

Your email address will not be published. Required fields are marked *