Select/Move/Copy image files with a specific name in its filename using Python

huangapple go评论64阅读模式
英文:

Select/Move/Copy image files with a specific name in its filename using Python

问题

我正试图移动具有特定名称的图像文件。

文件名如下:

文件名 1 = This_is_a_BAD_image.jpg
文件名 2 = This_is_a_GOOD_image.jpg

文件名由下划线分隔。我想要特别剪切或“移动”文件名中包含“GOOD”的图像(基本上是文件名 2)到另一个文件夹。然后,我只想复制并粘贴文件名中包含“BAD”的图像。我尝试使用startswith()变量,但由于我想要的文本不在第一部分中,所以它不起作用。

由于我的谷歌搜索没有结果,所以我还没有尝试过任何方法。感谢任何帮助,谢谢!

英文:

I am trying to move certain image files with a specific name in its filename.

The filename is as follows:

filename 1 = This_is_a_BAD_image.jpg
filename 2 = This_is_a_GOOD_image.jpg

The filenames are separated by underscores. I want to specifically cut and paste or "move" the images with "GOOD" in its filename (basically filename 2) to another folder. And then I want to just copy and paste the images with "BAD" in its filename. I tried using startswith() variable but since the text that I want is not in the first part, it doesn't work.

I haven't tried anything yet since my google search came out empty. Appreciate any help, thank you!

答案1

得分: 2

使用shutil模块来复制和移动文件,如果文件名中包含GOOD则移动,如果包含BAD则复制:

source_folder = '/path/to/source/folder'
destination_folder = '/path/to/destination/folder'

for filename in os.listdir(source_folder):
    if 'GOOD' in filename:
        shutil.move(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))
    elif 'BAD' in filename:
        shutil.copy(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))
英文:

how about using shutil module to copy and move files, if GOOD is find in the filename then move, if 'BAD' found in the filename, copy it :

source_folder = '/path/to/source/folder'
destination_folder = '/path/to/destination/folder'

for filename in os.listdir(source_folder):
    if 'GOOD' in filename:
        shutil.move(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))
    elif 'BAD' in filename:
        shutil.copy(os.path.join(source_folder, filename), os.path.join(destination_folder, filename))

huangapple
  • 本文由 发表于 2023年6月9日 09:17:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定