小编给大家分享一下Python复制文件中内容的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

Python复制文件中内容的方法:

1、使用shutil.copyfile(file1,file2)方法复制

file1为需要复制的源文件的文件路径,file2为目标文件的文件路径+文件名.

如下:将c盘中A文件夹下的0.png复制到D盘中B文件夹下并重命名为1.png.

src_file='C:\\A\\0.png'dst_file='D:\\B\\1.png'shutil.copyfile(src_file,dst_file)

2、使用.shutil.copy(文件1,文件2)方法复制

defcopy(src,dst):"""copydataandmodebits("cpsrcdst")Thedestinationmaybeadirectory."""ifos.path.isdir(dst):dst=os.path.join(dst,os.path.basename(src))copyfile(src,dst)copymode(src,dst)

3、shutil.copyfileobj(文件1,文件2):将文件1的数据覆盖copy给文件2。

importshutilf1=open("1.txt",encoding="utf-8")f2=open("2.txt","w",encoding="utf-8")shutil.copyfileobj(f1,f2)

看完了这篇文章,相信你对Python复制文件中内容的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!