Home  >  Article  >  Backend Development  >  How to delete or move specified images in batches with Python?

How to delete or move specified images in batches with Python?

PHPz
PHPzforward
2023-04-21 13:55:081557browse

1. Batch delete images with specified names

Before deletion, the path [D:\basic\aligned] includes the following images, including images starting with test and images starting with train.

The following code implements the deletion of all images named starting with test under the specified path, that is, [D:\basic\aligned].

# 批量删除指定名称的图像
root = r'D:\basic\aligned'
for file in os.listdir(root):
    if file.startswith('test'): # 删除root路径下 命名以'test'开头的图像
        os.remove(os.path.join(root, file))

2. Batch move images with specified names

Before moving, the original path, that is, [D:\basic\aligned] includes the following images. There are already images named starting with test. There are also images starting with train.

The target path, that is, there is no image under [D:\compound\aligned]

The following code implements all names in the original path [D:\basic\aligned] starting with train The image is moved to the target path [D:\compound\aligned].

src = r'D:\basic\aligned' # 原文件夹
dst = r'D:\compound\aligned' # 目标文件夹
for file in os.listdir(src):
    if file.startswith('train'): # 移动原文件夹中 命名以test开头的图像 到目标文件夹
        shutil.move(os.path.join(src, file),os.path.join(dst, file))

After moving, you can see that only the images starting with test are left in the original path, and all files starting with train have been moved to the target path.

The above is the detailed content of How to delete or move specified images in batches with Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete