python将文件夹A中的指定文件复制到文件夹B中and批量删除指定文件名的文件
python将文件夹A中的指定文件复制到文件夹B中
复制文件file的核心语法: 使用shutil模块
中的shutil.copy(source, direction)
实现将文件source复制到文件夹direction下,并重命名Copy文件。
shutil.copy(source_file_abs_path, direction_file_abs_path)
# 复制source中文件到direction下。
# 导入所需库
import pandas as pd
import numpy as np
import os,re
import shutil
pd.set_option('display.max_columns',None)
pd.set_option('display.max_rows',None)
pd.set_option('expand.frame_repr',False)
print('import succed!')
### 定义Copy的目标文件夹
# .xml格式的标注文件的direction指定路径
direction_xlm_path = r'/Users/edz/Documents/yandi_data/taishi_loading/train_sets/train_xlm'
### 定义Copy的原始文件夹
# 标注文件的source指定路径
source_xlm_path = r'/Users/edz/Documents/yandi_data/taishi_loading/file_xml'
# 复制source下的.xml格式文件到对应的direction下的文件夹
#################(1) 首先复制.xlm文件
for roots,dirs,files in os.walk(source_xlm_path):
if roots == '/Users/edz/Documents/yandi_data/taishi_loading/file_xml': # 过滤掉第一层主root目录
pass
else:
print(roots)
n = 0 # 初始化统计每个文件夹下复制了多少个文件
for file_item in files:
# print(file_item)
if file_item.endswith('.xml') and os.path.exists(direction_xlm_path + '/' + file_item) == False:
source_xlm_file_abs_path = os.path.join(roots, file_item) # 获得每一个欲copy文件的绝对路径
# print(source_xlm_file_abs_path)
direction_xlm_file_abs_path = os.path.join(direction_xlm_path,file_item) # 定义copy文件的目标路径
# print(direction_xlm_file_abs_path)
shutil.copy(source_xlm_file_abs_path, direction_xlm_file_abs_path) # 复制source中文件到direction下
n += 1 # 文件数累加
else:
pass
print('文件夹{}中符合要求的图片有{}张'.format(roots, n))
批量删除指定文件
删除指定文件名的文件,使用os.remove(file_remove_abs_path)
来实现(备注:file_remove_abs_path为欲删除的文件绝对路径)。
# 批量删除无标注的图片
# (1)读入准备移除的文件名list
list_remove = []
for roots, dirs, files in os.walk(direction_xlm_path):
for file in files:
if file.endswith('.xml'): # 排除隐藏文件的干扰
list_remove.append(file)
else:
pass
# 删除list_remove中的文件
for i in range(len(list_remove)):
file_remove_abs_path = direction_image_path + '/' +list_remove[i]
print(file_remove_abs_path)
os.remove(file_remove_abs_path)