'Move images with respect to their names
I have 10 images (123.vid1.png, 123.vid5.png, 123.vid8.png, 146.vid1.png, 146.vid5.png, 146.vid6.png, 191.vid2.png, 191.vid2.png, 191.vid5.png, 191.vid10.png) in a folder. I want to move the images with their names (123, 146, 191) to their respective folder. Folder 123 contains (123.vid1.png, 123.vid5.png, 123.vid8.png) Folder 146 contains (146.vid1.png, 146.vid5.png, 146.vid6.png) Folder 191 contains (191.vid2.png, 191.vid2.png, 191.vid5.png, 191.vid10.png)
import os
path = "/home/samples/"
files = os.listdir(path)
def Convert(string):
li = list(string.split(" "))
return li
def unique(list1):
list_set = set(list1)
unique_list = (list(list_set))
for x in unique_list:
print (x)
for file in files:
root, ext = os.path.splitext(file)
name = root.split(".")[0]
listing = Convert(name)
print(listing)
Solution 1:[1]
def move_images_to_folders(list_of_images):
for image in list_of_images:
if image.split('.')[0] == '123':
shutil.move(image, '123')
elif image.split('.')[0] == '146':
shutil.move(image, '146')
elif image.split('.')[0] == '191':
shutil.move(image, '191')
def main():
list_of_images = os.listdir()
move_images_to_folders(list_of_images)
def move_images_to_folders(dir_path):
import os
import shutil
import glob
images = glob.glob(dir_path + '/*.png')
folders = list(set([image.split('.')[0] for image in images]))
for folder in folders:
if not os.path.exists(dir_path + '/' + folder):
os.makedirs(dir_path + '/' + folder)
for image in images:
shutil.move(image, dir_path + '/' + image.split('.')[0] + '/' + image)
if __name__ == '__main__':
import sys
dir_path = sys.argv[1]
move_images_to_folders(dir_path)
print('Done!')
Haven't tested e2e. But this should do.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
