美文网首页
Python的shutil模块中文件的复制操作

Python的shutil模块中文件的复制操作

作者: 逍遥_yjz | 来源:发表于2022-04-26 19:43 被阅读0次

shutil.copyfile

shutil.copyfile(src, dst):将名为src的文件的内容复制到名为dst的文件中 。

  • src是具体的文件的路径
  • dst是具体的文件路径+你想要赋给复制文件的名字 (必须包含你想要创建的文件名)

src, dst是文件名


shutil.copy

shutil.copy(source, destination)
shutil.copy() 函数实现文件复制功能,将 source 文件复制到 destination 文件夹中,两个参数都是字符串格式。如果 destination 是一个文件名称,那么它会被用来当作复制后的文件名称,即等于 复制 + 重命名。

source一定是文件名,destination可以是文件名也可以是文件夹名

举例如下:

import os
import shutil

src="./data_copy"#原文件夹路径
des="./result2"#目标文件夹路径

for file in os.listdir(src):
    #遍历原文件夹中的文件
    full_file_name = os.path.join(src, file)#把文件的完整路径得到
    print("要被复制的全文件路径全名:",full_file_name)
    result_file_name = os.path.join(des, file)
    # 用于判断某一对象(需提供绝对路径)是否为文件
    if os.path.isfile(full_file_name):
        print(result_file_name)
        # shutil.copy函数放入原文件的路径文件全名  然后放入目标文件夹
        shutil.copy(full_file_name, result_file_name)
# 复制文件到指定的文件目录中,result_file_name必须精确到文件名
shutil.copyfile(full_file_name, result_file_name)

shutil.copy('./data_copy', './result2')
# PermissionError: [Errno 13] Permission denied: './data_copy'

shutil 模块

shutil.copyfile( src, dst)   #从源src复制到dst中去。 如果当前的dst已存在的话就会被覆盖掉
shutil.move( src, dst)  #移动文件或重命名
shutil.copymode( src, dst) #只是会复制其权限其他的东西是不会被复制的
shutil.copystat( src, dst) #复制权限、最后访问时间、最后修改时间
shutil.copy( src, dst)  #复制一个文件到一个文件或一个目录
shutil.copy2( src, dst)  #在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,
类似于cp –p的东西
shutil.copy2( src, dst)  #如果两个位置的文件系统是一样的话相当于是rename操作,只是改名;
如果是不在相同的文件系统的话就是做move操作
shutil.copytree( olddir, newdir, True/Flase) #把olddir拷贝一份newdir,如果第3个参数是True,
则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本
来替代符号连接
shutil.rmtree( src )   #递归删除一个目录以及目录内的所有内容

相关文章

  • Python复制文件命令合集

    python的shutil模块提供了便捷的复制文件命令 shutil.copy(srcfile,dstfile) ...

  • python常用文件操作总结

    python 移动文件或文件夹操作。python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法...

  • Python os 常用 模块

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 os.getcwd() ...

  • python os模块 文件操作

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 os模块 得到当前工作目...

  • python_对文件的处理

    !取前辈之精华,武装自己 python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。...

  • python的读写 ,创建 ,文件

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,即当前...

  • 关于python文件操作

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,即当前...

  • python 文件操作函数

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,即当前...

  • python os模块总结

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,即当前...

  • python 文件操作

    python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块。 得到当前工作目录,即当前...

网友评论

      本文标题:Python的shutil模块中文件的复制操作

      本文链接:https://www.haomeiwen.com/subject/eoshyrtx.html