网络编程
位置:首页>> 网络编程>> Python编程>> python利用os模块编写文件复制功能——copy()函数用法

python利用os模块编写文件复制功能——copy()函数用法

作者:Three123v  发布时间:2023-01-20 16:11:56 

标签:python,os,文件复制,copy

我就废话不多说了,大家还是直接看代码吧~


#文件复制
import os
src_path=r'E:\Pycharm\python100题\代码'
target_path=r'E:\Pycharm\python100题\123'

#封装成函数
def copy_function(src,target):
if os.path.isdir(src) and os.path.isdir(target):
 filelist=os.listdir(src)
 for file in filelist:
   path=os.path.join(src,file)
   if os.path.isdir(path):
    copy_function(path,target)
   with open(path,'rb') as rstream:
    container=rstream.read()
    path1=os.path.join(target,file)
    with open(path1,'wb') as wstream:
     wstream.write(container)
 else:
  print('复制完毕!')
copy_function(src_path,target_path)

#改进后的文件复制,可以递归复制文件,之前的文件复制不能复制文件夹
import os
src_path=r'E:\Pycharm\python100题\代码'
target_path=r'E:\Pycharm\python100题\123'

def copy_function(src,target):
if os.path.isdir(src) and os.path.isdir(target):
 filelist=os.listdir(src)
 for file in filelist:
   path=os.path.join(src,file)
   if os.path.isdir(path):   #判断是否为文件夹
    target1=os.path.join(target,file)
    os.mkdir(target1) #在目标文件下在创建一个文件夹

copy_function(path,target1)
   else:
    with open(path, 'rb') as rstream:
     container = rstream.read()
     path1 = os.path.join(target, file)
     with open(path1, 'wb') as wstream:
      wstream.write(container)
 else:
  print('复制完毕!')
copy_function(src_path, target_path)

补充知识:python复制文件夹(包含os库多种函数的)

看代码吧~


import os#调出os库
#文件的复制
def mycopy(file1,file2):#定义一个mycopy函数用于复制文件

f1=open(file1,"rb")#以读取模式打开file1
f2=open(file2,"wb")#以清空写模式打开file2

content = f1.readline()#将第一行数据赋给content
while len(content)>0:#如果读取到的数据长度不为0则循环执行
f2.write(content)#在file2里写下content
content=f1.readline()#再读一行赋给content

f1.close()#关闭file1
f2.close()

#自定义目录复制函数
def copydd(dir1,dir2):#定义复制文件夹函数coppydd
#获取被复制目录中的所有文件信息
dlist = os.listdir(dir1)#以列表模式赋给dlist
#创建新目录
os.mkdir(dir2)#创建新文件夹dir2
#遍历所有文件并执行文件复制
for f in dlist:#让f在dlist中遍历
#为遍历的文件添加目录路径
file1 = os.path.join(dir1,f)#将f遍历出的文件名给file1(dir1+f即路径+文件名)
file2 = os.path.join(dir2,f)#同样也给file2
#判断是否是文件
if os.path.isfile(file1):#判断是否为文件的方式为os库中的函数 os.path.isfile(文件名)
mycopy(file1,file2)#调用自定义的mycopy函数复制文件
if os.path.isdir(file1):#如果是文件夹的话 那就调用自身(自身就是复制文件夹嘛)e而处理的不是dir1,dir2,是file1,file2,因为此时文件夹同文件一起被f遍历,此处判断的就是f遍历出的是文件还是文件夹
coppydd(file1,file2)#调用自身 递归思想

#测试
copydd("./aa","./bb")#当前文件夹中的aa文件夹复制到bb文件夹 没有会自动创建

来源:https://blog.csdn.net/Three123v/article/details/102772645

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com