![](/img/trans.png)
[英]How to copy files from the one folder to another if flag is True in dictionary
[英]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.