前言
我们从网上下载了一个大型教程,但有时并不需要所有的文件,我们只想要里面的PDF或者word之类的。可以借助python对该文件夹的文件批量复制到另一个指定文件夹中。有两种模式,一种只复制文件。第二种复制文件的完整路径
简介
get_all_file_by_type() :根据接收到的path 和type,获得该path下所有以type类型结尾的文件
get_all_file_by_string(): 根据接收到的path 和 list, 获得该path下所有的,包含list 里字符串的文件
copy_file_by_type(): 根据接收到的old_path,和type,调用get_all_file_by_type()方法。根据条件选择不同的执行代码
copy_file_by_string():同理,不过它调用的是get_all_file_by_string()方法
代码
1、复制文件的完整路径
import os
import shutil
def get_all_file_by_type(path, type=()): # 获得以type类型结尾的所有文件,返回一个list
filelist = []
for a, b, c in os.walk(path):
for name in c:
fname = os.path.join(a, name)
if fname.endswith(type):
filelist.append(fname)
return filelist
def get_all_file_by_string(path, string_list):
filelist = []
for a, b, c in os.walk(path):
for name in c:
fname = os.path.join(a, name)
for string in string_list: # 遍历string_list,如果文件路径中包含string,那么append进filelist
if string in fname: # 如果只想要文件名符合条件,把fname换成name即可
filelist.append(fname)
break
return filelist
def copy_file_by_type(old_path, new_path, type=('doc', 'docx'), requird_dir=False):
try:
file_list = get_all_file_by_type(old_path, type=type) # 获得该路径下所有的type类型文件
if not os.path.exists(new_path): # 创建新的文件夹
os.makedirs(new_path)
if not requird_dir: # 如果仅复制文件
for file in file_list:
name = file.split("\\")[-1] # 获得文件名字
new_paths = os.path.join(new_path, name) # 与新路径拼接,获得完整的新路径
shutil.copy(file, new_paths)
print(new_paths + "成功")
if requird_dir:
for file in file_list:
name = file.split("\\")[-1] # 获得文件名字
new_paths = file.replace(old_path, new_path) # 将一个完整路径中,开始的路径替换成新的路径
dir = new_paths.split(name)[0] # 获得文件夹路径
if not os.path.exists(dir): # 创建新文件夹
os.makedirs(dir)
shutil.copy(file, new_paths)
print(new_paths + "成功")
except Exception as e:
print(e)
def copy_file_by_string(old_path, new_path, string_list, requird_dir=False):
try:
file_list = get_all_file_by_string(old_path, string_list=string_list) # 与上述一样,只不过这里调用的是get_all_file_by_string方法
if not os.path.exists(new_path):
os.makedirs(new_path)
if not requird_dir:
for file in file_list:
name = file.split("\\")[-1]
new_paths = os.path.join(new_path, name)
shutil.copy(file, new_paths)
print(new_paths + "成功")
if requird_dir:
for file in file_list:
name = file.split("\\")[-1]
new_paths = file.replace(old_path, new_path)
print(new_paths)
dir = new_paths.split(name)[0]
if not os.path.exists(dir):
os.makedirs(dir)
shutil.copy(file, new_paths)
print(new_paths + "成功")
except Exception as e:
print(e)
if __name__ == '__main__':
old_path = r"F:\aaaa"
new_path = r"F:\bbbb"
list = ["面试", "笔试", "题库", "题目"]
copy_file_by_string(old_path=old_path, new_path=new_path, string_list=list, requird_dir=False)
# type = ('docx','doc',"pdf","md")
# copy_file_by_type(old_path=old_path, new_path=new_path, type=type, requird_dir=True)
总结
- 可以加try-except防止程序停止