簡體   English   中英

如何將奇數文件從一個文件夾復制到另一個文件夾?

[英]How to copy odd numbered Files from one folder to another folder?

我在一個文件夾中有大約 1000 張圖像名稱為“image290.jpg、image291.jpg、image292.jpg、...”的圖像。

我想將所有帶有奇數的圖像(例如“image291.jpg,image293.jpg,image295.jpg,...”)復制到另一個文件夾。

如何使用 python 代碼做這些事情?

這是我使用 shutil 庫的解決方案:

import os
import shutil
images = os.listdir(your_dirctory_name)
for image_name in images:
    if int(image_name[5:-4]) % 2 == 1:
        shutil.copy(your_dirctory_name + "/" + image_name, your_output_directory_name)

您可以使用shutil.copyfile移動文件:

from shutil import copyfile
import os
import re

origin = '/you/folder/with/images'
paths = os.listdir(origin)
dst_dir = '/your/destination/dir/path'

for src in paths:
    r = re.search(r'image(\d*)\.jpg', src)

    if r and int(r.group(1)) % 2 != 0:
        copyfile(os.path.join(origin, src), os.path.join(dst_dir, r.group()))

這就是我想出的:

import re

file_names = ["image290.jpg", "image291.jpg", "image292.jpg", "image293.jpg", "image294.jpg", "image295.jpg"]

pattern = re.compile(r"[a-zA-Z]+(\d+)\.[a-zA-Z]+")

for file in file_names:
    if int(re.search(pattern, file).group(1))%2 != 0:
        print(f"copying odd numbered file {file} to blablah/bla")
    else:
        print(f"skipping even numbered file {file}")

Output:

skipping even numbered file image290.jpg
copying odd numbered file image291.jpg to blablah/bla
skipping even numbered file image292.jpg
copying odd numbered file image293.jpg to blablah/bla
skipping even numbered file image294.jpg
copying odd numbered file image295.jpg to blablah/bla
import os
import re
import shutil

base_dir= os.path.dirname(__file__)#it will fetch the path of folder in which your code file resides
input_directory_name= os.path.join(base_dir+'/all_images/')
output_directory_name= os.path.join(base_dir+'/odd_numbered_images/')
pattern = re.compile(r"[a-zA-Z]+(\d+)\.[a-zA-Z]+")
for file in os.listdir(base_dir+'/all_images/'):

if int(re.search(pattern, file).group(1))%2 != 0:
    shutil.copy(input_directory_name+ file, output_directory_name)
    print(f"copying odd numbered file {file} to "+str(output_directory_name))
else:
    print(f"skipping even numbered file {file}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM