Home > Back-end >  Creating subfolder and storing specified files/images in those
Creating subfolder and storing specified files/images in those

Time:10-03

During one of my projects, I faced this challenge: There is a folder named Project, and inside that, there are multiple images (say 100 images), and each has been named sequentially like the first image name is imag_0, 2nd image name is img_2,....imag_99. Now, based on some conditions, I need to separate out some images say img_5, img_10, img_30, img_88, img_61. My question will be, is there any way to filter out these images and make a folder inside the folder Project named "the odd ones" and store those specified images?

One extra help will be in my case. Suppose I have hundreds of such Projects folders in a sequential way Projects_1, Projects_2, Projects_3,....., Projects_99, and each contains hundreds of pictures. Can it be possible to separate all the specified photos and store them inside a separate folder inside each Projects_n folder, assuming the photos we have to separate out and store differently will be the same for each Projects_n folder? Please help me with this. Thank you!

CodePudding user response:

For the first problem you can lookup to the below pseudo-code (you have to specify the target function). Instead, for the second problem you should provide more details;

from glob import glob
import itertools
import shutil
import os

# Creating a funtion to check if filename 
# is a target file which has to be moved:
def is_target(filename):
    if ... return True
    else return False

dirname = "some/path/to/project"

# Creating a list of all files in dir which
# could be moved based on type extension:
types = ('*.png', '*.jpeg')
filepaths = list(itertools.chain(*[glob(os.path.join(dirname, f"*.{t}")) for t in types]))

# Finding the files to move:
filepaths_to_move = []
for filepath in filepaths:
    if is_target(os.path.basename(filepath)):
        filepaths_to_move.append(filepath)

# Creating the new subfolder:
new_folder_name = "odd_images"
new_dir = os.path.join(dirname, new_folder_name)
if not os.path.exists(new_dir): os.makedirs(new_dir)

# Moving files into subfolder:
for filepath in filepaths_to_move:
    basename = os.path.basename(filepath)
    shutil.move(source, os.path.join(filepath, os.path.join(dirname, basename))) 

CodePudding user response:

Here is the logic.make necessary improvements for your use case

    project_dir = "project_dir"
    move_to_dir = os.path.join(project_dir,"move_to_dir")
    
    files = [os.path.join(project_dir,file) for file in os.listdir(project_dir)]
    filenames_to_filter = "test1.txt,test2.txt"
    if not os.path.exists(move_to_dir):
       os.makedirs(move_to_dir)

    for(file in files):
        if os.path.basename(file) in filenames_to_filter:
           shutil.move(file,move_to_dir)
    `
      
  • Related