Python从入门到高手(内部资源-配学习资料)_哔哩哔哩_bilibili
import os
# 文件复制
src_path = r'C:\Users\RSB\Desktop\Python文件夹\p1'
target_path = r'C:\Users\RSB\Desktop\Python文件夹\p2'
# 封装成函数
def copy(src, target):
if os.path.isdir(src) and os.path.isdir(target):
filelist = os.listdir(src) # ['','','']
for file in filelist: # aa.txt
path = os.path.join(src, file)
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(src_path, target_path)
---------------------------------------------------------------------------------
import os
# 文件复制
src_path = r'C:\Users\RSB\Desktop\Python文件夹\p1'
target_path = r'C:\Users\RSB\Desktop\Python文件夹\p3'
filelist = os.listdir(src_path)
print(filelist)
def copy(src_path, target_path):
# 获取文件夹里面内容
filelist = os.listdir(src_path)
# 遍历列表
for file in filelist:
# 拼接路径
path = os.path.join(src_path, file)
tar_path = target_path
# 判断是文件夹还是文件
if os.path.isdir(path):
tar_path = os.path.join(tar_path, file)
os.mkdir(tar_path)
# 递归调用copy
copy(path, tar_path)
else:
# 不是文件夹则直接进行复制
with open(path, 'rb') as rstream:
container = rstream.read()
path1 = os.path.join(target_path, file)
with open(path1, 'wb') as wstream:
wstream.write(container)
else:
print('复制完成!')
# 调用copy
copy(src_path, target_path)
|