python将文件夹A中的指定文件复制到文件夹B中and批量删除指定文件名的文件

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yale曼陀罗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值