Home > OS >  Python - Automate movement of files to folders that corresponds with its respective number
Python - Automate movement of files to folders that corresponds with its respective number

Time:12-15

I have a script that takes cmd argument and moves it into the folder with the respective number.

For example, I have 20 folders named Episode 1 through Episode 20, and I have a total of 120 files, 5 files per folder (file1-ep 1, file2-ep1 would move into folder "episode 1", all the way to file1-ep20, file2-ep20 would move into folder "episode 20", etc).

I already have the script to move the file, it just requires me to enter cmd line argument move.py 1 move.py 2, etc.

Basically, I want the program to loop automatically instead of asking for user input (I would just need to supply the start and stop numbers) How can I make a loop so that it moves all the respective files into the folders without any user input?

My current script

import os
import sys
import shutil

path = "/Users/Macbook/Final Cut Pro/"

destination_path = f"/Users/Macbook/Final Cut Pro/episode {sys.argv[1]}/"

for (root, dirs, file) in os.walk(path):
    for f in file:
        f = f.lower()
        if check_file(sys.argv[1])in f:
            source = path   f
            destination = destination_path   f
            print(f)
            # shutil.move(source, destination)

I've tried putting the nested for loops into another for loop.

for i in range (1,21)

    for loop
    for loop

CodePudding user response:

Turns out my idea of an outer loop was correct, only I was using sys.argv[i] instead of i. I also have to move the destination path inside the loop.

for i in range(int(sys.argv[1]), int(sys.argv[2])   1):
    destination_path = f"/Users/Macbook/Final Cut Pro/episode {i}/"
    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
            f = f.lower()
            if checked_files(i):
               #move files

CodePudding user response:

If the name of your file is in the following format file1-ep 1. they you try this

start_number = 1
end_number = 20
for i in range(start_number, end_number 1):
    for (root, dirs, file) in os.walk(path):
        for f in file:
            f = f.lower()
            if i == int(re.findall(r'\d ', f)[0]):
                source = path   f
                destination = destination_path   f
                print(f)
                shutil.move(source, destination)
  • Related