#导入os模块
import os
'''
1.不考虑文件夹中有文件夹
sourcefile = r'D:\PyCharm\PycharmProjects\文件操作专用\source'
targetfile = r'D:\PyCharm\PycharmProjects\文件操作专用\target'
实现两个文件的拷贝从sourcefile ---> targetfile
def copy(sourcefile,targetfile):
1.要找到文sourcefile文件夹中的文件有什么 得到的是一个列表
2.遍历这个文件夹,得到文件的 文件名+扩展名
判断这个文件夹中,是否嵌套文件夹
3.拼接文件的绝对路径+文件名+扩展名
4.读文件
5.将读到的文件写入目标文件
'''
sourcefile = r'D:\PyCharm\PycharmProjects\文件操作专用\source' #在哪里拷贝
targetfile = r'D:\PyCharm\PycharmProjects\文件操作专用\target' #拷贝到那里去
#定义拷贝函数(只能拷贝)
def copy(sourcefile,targetfile):
'''
:param sourcefile: 要拷贝文件夹的路径
:param targetfile: 目标文件夹
:return:
'''
#获的要拷贝文件夹中的所有文件[文件夹,文件]
list_dir = os.listdir(sourcefile) # ['a.txt', 'b.txt', 'c.docx', '图片.jpg']
#循环得到文件夹中的每一个文件的文件名+扩展名
for filename in list_dir:
#拼接文件(要拷贝文件+文件名+扩展名)得到绝对路径 os.path.join( ,)
rpath = os.path.join(sourcefile,filename)
#判断是否是文件夹,是真,不是假
if not os.path.isdir(rpath):
#从来源文件夹中读取文件通过'rb'的形式,可能存在图片音乐文本等
#这里的rpath是来源文件+文件名+扩展名
with open(rpath,'rb') as rstream:
#将读到的内容保存在something里面
something = rstream.read()
#拼接目标文件(目标文件夹+文件名+扩展名)
wpath = os.path.join(targetfile,filename)
#写文件,通过'wb'
with open(wpath,'wb') as wstream:
#写文件 格式:流.write(写的内容)
wstream.write(something)
#遇到的是文件夹
else:
print('{}是文件夹,该函数不支持拷贝文件夹'.format(rpath))
#拷贝成功:for else 这里else的执行时机是:for循环正常结束后执行的代码,如果遇到了breakelse将不再执行
else :
print('拷贝成功!')
#调用copy函数
copy(sourcefile,targetfile)