正则表达式选择特定文件进行复制
文件复制
使用shutil库中的copy函数进行复制。
def copy_file(from_dir, to_dir, Name_list):if not os.path.isdir(to_dir):os.mkdir(to_dir)for name in Name_list:try:# print(name)if not os.path.isfile(os.path.join(from_dir, name)):print("{} is not existed".format(os.path.join(from_dir, name)))shutil.copy(os.path.join(from_dir, name), os.path.join(to_dir, name))# print("{} has copied to {}".format(os.path.join(from_dir, name), os.path.join(to_dir, name)))except:# print("failed to move {}".format(from_dir + name))pass# shutil.copyfile(fileDir+name, tarDir+name)print("{} has copied to {}".format(from_dir, to_dir))
正则表达式得到文件名列表
使用re库实现字符串匹配得到用户想要的文件夹名列表。参数pattern决定匹配file_list中哪些文件名。
def obtain_certrain_name_list(file_list, pattern):result = [re.findall(pattern, file) for file in file_list]flattened = sum(result, [])post_result = list(set(flattened))return post_result
总体代码示例
import re
import os
import random
import shutildef copy_file(from_dir, to_dir, Name_list):if not os.path.isdir(to_dir):os.mkdir(to_dir)# 1# name_list = os.listdir(from_dir)# # 2# sample = random.sample(pathDir, 2)# print(sample)# 3for name in Name_list:try:# print(name)if not os.path.isfile(os.path.join(from_dir, name)):print("{} is not existed".format(os.path.join(from_dir, name)))shutil.copy(os.path.join(from_dir, name), os.path.join(to_dir, name))# print("{} has copied to {}".format(os.path.join(from_dir, name), os.path.join(to_dir, name)))except:# print("failed to move {}".format(from_dir + name))pass# shutil.copyfile(fileDir+name, tarDir+name)print("{} has copied to {}".format(from_dir, to_dir))def obtain_certrain_name_list(file_list, pattern):result = [re.findall(pattern, file) for file in file_list]flattened = sum(result, [])post_result = list(set(flattened))return post_resultif __name__ == '__main__':from_path = "./Augment_from_files/"to_path = "./Augment_to_files/"if not os.path.exists(to_path):os.mkdir(to_path)from_file_list = os.listdir(from_path)# part1: copy gt image from from_path = "./Augment_from_files/"gt_image_list = obtain_certrain_name_list(from_file_list, ".+_gt.png")print(gt_image_list)gt_to_path = to_path + "annos"if not os.path.exists(gt_to_path):os.mkdir(gt_to_path)copy_file(from_path, gt_to_path, gt_image_list)# part2: copy image from from_path = "./Augment_from_files/"image_list = obtain_certrain_name_list(from_file_list, ".+[^_show].jpg")print(image_list)image_to_path = to_path + "images"if not os.path.exists(image_to_path):os.mkdir(image_to_path)copy_file(from_path, image_to_path, image_list)