python批量将前缀名字一样的文件拷贝到一起

描述:a文件夹存放1.jpg、2.jpg、3.jpg
b文件夹存放1.txt、3.txt
将a和b前缀同名的文件拷贝到root_path/check下,执行完后新文件夹有1.jpg、3.jpg、1.txt、3.txt

import os
import shutil

root_path = r"D:\desktop\check/"
img_path = r"D:\desktop\fine_cantilever_base\images/" #图像文件夹
txt_path = r"D:\desktop\fine_cantilever_base\xml/" #标签文件夹
def train_test_move(txt_path,root_path,img_path):
    if not os.path.exists(root_path):
        os.makedirs(root_path)
    files = os.listdir(txt_path)
    for file in files:
        shutil.copy(txt_path+file,root_path)
        shutil.copy(img_path+file[:-3]+"jpg",root_path)
train_test_move(txt_path,root_path,img_path)
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
批量修改Python文件文件名,可以使用os模块中的listdir函数来获取指定目录下的所有文件名。然后,可以使用字符串的replace方法或正则表达式来替换文件名中的特定内容。根据提供的引用内容,有两种方法可以实现文件名的批量修改。 方法一(使用os.listdir函数): 1. 使用os.listdir函数获取指定目录下的所有文件名。 2. 遍历文件名列表,对每个文件名进行修改,可以添加前缀或使用replace方法替换特定内容。 3. 使用os.rename函数将修改后的文件名应用到文件。 方法二(使用os.walk函数): 1. 使用os.walk函数遍历指定目录及其子目录下的所有文件。 2. 遍历每个文件,对文件名进行修改,可以添加前缀或使用replace方法替换特定内容。 3. 使用os.rename函数将修改后的文件名应用到文件。 根据提供的引用内容,可以参考以下示例代码来批量修改Python文件文件名: ```python import os def rename_files(): path = r'E:\我的学习\编程\Python\PythonTest2\Test2' # 修改为指定的目录路径 for filename in os.listdir(path): if filename.endswith('.py'): # 只修改指定类型的文件名,如.py文件 new_filename = filename.replace('old_content', 'new_content') # 使用replace方法替换特定内容 os.rename(os.path.join(path, filename), os.path.join(path, new_filename)) # 应用修改后的文件名 if __name__ == '__main__': rename_files() ``` 请注意,以上示例代码中的路径、需要替换的内容以及替换后的内容需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值