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

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

PHPz
Release: 2023-04-21 13:55:08
forward
1637 people have browsed it

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))
Copy after login

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))
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template