??
需求:把一個文件夾內(nèi)(包含子文件夾)的所有文件復(fù)制到另一個文件夾下
#coding=utf-8
import os
import shutil
old_path = r'F:\1' # 要復(fù)制的文件所在目錄
new_path = r'F:\2' #新路徑
def FindFile(path):
for ipath in os.listdir(path):
fulldir = os.path.join(path, ipath) # 拼接成絕對路徑
print(fulldir) #打印相關(guān)后綴的文件路徑及名稱
if os.path.isfile(fulldir): # 文件,匹配->打印
shutil.copy(fulldir,new_path)
if os.path.isdir(fulldir): # 目錄,遞歸
FindFile(fulldir)
FindFile(old_path)
注:如果不需要復(fù)制文件夾內(nèi)的子文件夾可刪除下面這2行
if os.path.isdir(fulldir): # 目錄,遞歸
??FindFile(fulldir)引用
?
進階需求代碼:
一、把一個文件夾內(nèi)(包含子文件夾)指定后綴的文件復(fù)制到另一個文件夾
#coding=utf-8
import os
import shutil
old_path = r'F:\1' # 要復(fù)制的文件所在目錄
new_path = r'F:\2' #新路徑
suffix = '.xml' #要復(fù)制的文件后綴
def FindFile(path, tagfile):
for ipath in os.listdir(path):
fulldir = os.path.join(path, ipath) # 拼接成絕對路徑
if tagfile in os.path.split(fulldir)[1]: # 查找包含了指定關(guān)鍵字的文件
print(fulldir) #打印相關(guān)后綴的文件路徑及名稱
if os.path.isfile(fulldir): # 文件,匹配->打印
shutil.copy(fulldir,new_path)
if os.path.isdir(fulldir): # 目錄,遞歸
FindFile(fulldir, tagfile)
FindFile(old_path, suffix)
?
二、把一個文件夾內(nèi)(包含子文件夾)指定后綴的文件復(fù)制到另一個文件夾并生成多份指定名稱的文件文章來源:http://www.zghlxwxcb.cn/news/detail-549690.html
#coding=utf-8
import os
import re
import shutil
old_path = r'F:\1' # 要復(fù)制的文件所在目錄
new_path = r'F:\2' #新路徑
suffix = '.xml' #要復(fù)制的文件后綴
def FindFile(path, tagfile):
for ipath in os.listdir(path):
fulldir = os.path.join(path, ipath) # 拼接成絕對路徑
print(fulldir) #打印相關(guān)后綴的文件路徑及名稱
if os.path.isfile(fulldir): # 文件,匹配->打印
if tagfile in os.path.split(fulldir)[1]: # 查找包含了指定關(guān)鍵字的文件
data_red = fulldir.split("\\")[len(re.split(r'\\',path))] # 拿到文件名稱,也是項目名稱
print(data_red) #打印相關(guān)后綴的文件名稱
for i in range(1,66): #目的是復(fù)制65份data_red文件
data_re = re.sub(r'\d+', str(i), data_red) #提取需要改的data_red字節(jié)
shutil.copy(r"{0}\{1}".format(old_path,data_red), r"{0}\{1}".format(new_path,data_re))
if os.path.isdir(fulldir): # 目錄,遞歸
FindFile(fulldir, tagfile)
FindFile(old_path, suffix)
?
執(zhí)行代碼效果圖:
?
??old_path下文件:
?
??new_path下文件部分截圖:文章來源地址http://www.zghlxwxcb.cn/news/detail-549690.html
到了這里,關(guān)于python怎么把一個文件夾內(nèi)的文件復(fù)制到另外一個文件夾(進階重命名復(fù)制)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!