Python如何复制文件中的内容
发布时间:2026-04-28 15:49:16

复制文件中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的数据覆盖到文件2。
importshutil
f1=open("1.txt",encoding="utf-8")
f2=open("2.txt","w",encoding="utf-8")
shutil.copyfileobj(f1,f2)请关注Python视频教程栏目,了解更多Python知识。
下一篇 返回列表
