学习记录04:如何用python将含有特定字符名的图像或文件夹移动到另外一个文件夹

应用场景:

将含有特定字符名的图像或文件夹移动到另外一个文件夹

解决方案:

1.将指定文件移动到指定文件夹

import shutil
source_file_path0 = 'D:/pycharm/chip_5_12/data/train/b/1.txt'		#表达地址的两种格式,都是可以的
new_file_path0 = 'D:\\pycharm\\chip_5_12\\data\\train\\a'
shutil.move(source_file_path0, new_file_path0)

2.将指定文件夹移动到指定文件夹

注意:源地址最后一个文件是你想移动的文件,目标地址最后一个文件是你想放入哪个文件夹

import shutil
source_file_path0 = 'D:/pycharm/chip_5_12/data/train/b'		
new_file_path0 = 'D:\\pycharm\\chip_5_12\\data\\train\\a'
shutil.move(source_file_path0, new_file_path0)

3.将含有特定名称的文件夹和文件移动到指定文件夹

文件排放示例如下:
在这里插入图片描述

完整代码如下:

import os
import shutil


source_file_path0 = 'D:/pycharm/chip_5_12/data/train/'
name0 = os.listdir(source_file_path0)
new_file_path0 = 'D:\\pycharm\\chip_5_12\\data\\train\\a'
for i in name0:  		#遍历name0中所有文件名
    if 'f' in i:		#判断字符f是否存在于文件名中
        shutil.move(source_file_path0 + i, new_file_path0)		#移动文件
print(name0)

name0 = os.listdir(source_file_path0)是将D:/pycharm/chip_5_12/data/train下的文件名读取到name0列表,其存储值打印如下:
在这里插入图片描述
该段程序最终是将文件夹af移动到了文件夹a里,结果如图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43180908/article/details/116738105