#文件的复制
'''
原文件:c:\pl\girl.jpg
目标文件:c:\p2\girl.jpg
'''

#with 结合open使用,可以帮助我们自动释放资源

1 with stream=open(r'c:\pl\girl.jpg','rb') as srteam:
2     container=stream.read() #读取文件内容
3 
4     with open(r'c:\p2\girl.jpg','wb') as wstream:
5         wstream.write(container)
6 print('文件复制完成')

#模块:os.py
'''
os.path:
os.path.dirname(__file__) 获取当前文件所在的目录
os.path.join(path,'') 返回的是一个拼接后的新路径
'''

 1 import random
 2 import os
 3 print(os.path)
 4 path=os.path.dirname(__file__)  #获取当前文件所在的目录(绝对路径)
 5 print(path)
 6 print(type(path))
 7 result=os.path.join(path,'a1.jpg')  #在原来的文件夹下拼接一个文件的名字
 8 print(result)
 9 
10 
11 with open(r'c:\pl\girl.jpg','rb') as srteam:
12     container=stream.read() #读取文件内容
13     path=os.path.dirname(__file__)
14     path1=os.path.join(path,'a1.jpg') 
15 
16     with open(path1,'wb') as wstream:
17         wstream.write(container)

 

 1 #复制文件夹
 2 import os
 3 
 4 #文件复制
 5 src_path=r'c:\p1'
 6 target_path=r'c:\p2'
 7 
 8 #封装成函数
 9 def copy(src,target):
10     if os.path.isdir(src) and os.path.isdir(target):
11         filename=os.listdir(src)
12         for file in filelist:
13             path=os.path.join(src,file)
14             with open(path,'rb') as rstream:
15                 container=rstream.read()
16                 path1=os.path.join(target,file)
17                 with open(path1,'wb') as wstream:
18                     wstream write(container)
19         else:
20             print('复制完毕')
21 
22 copy(src_path,target_path)

 

作者:{admin-xiaoli}