[Solved] Copying a file and then printing the absolute path to its final destination [closed]


This code should solve your problem:

import os
import shutil

#lets say that the extension is mp4 but you can change it to the correct one
file_name="RRR_0010_V001.mp4"
file_name_parts = file_name.split('_')
#remove the extension for the last folder in the dir
file_name_parts[2] = file_name_parts[2].replace('.mp4', '')
directory = os.path.join(file_name_parts[0],file_name_parts[1],file_name_parts[2])
try:
    os.makedirs(directory)
except FileExistsError:
    with open('errors.log', 'a') as log:
        log.write('Error: File already exists.')

shutil.copy(file_name,directory)

This should make a directory based on your file name and copy the original file in there. But this works by default in the home dir, like C:\ in Windows and / in Linux. But I assume you already know how to change the dir to your preferred folder. But if you have any doubts, feel free to comment.

Edit:
For all the files in the cwd, the code is mostly the same.

import os
import shutil

#lets say that the extension is mp4 but you can change it to the correct one
def make_dir_with_file(file_name):
    file_name_parts = file_name.split('_')
    #remove the extension for the last folder in the dir
    file_name_parts[2] = file_name_parts[2].replace('.mp4', '')
    directory = os.path.join(file_name_parts[0],file_name_parts[1],file_name_parts[2])
    try:
        os.makedirs(directory)
    except FileExistsError:
        with open('errors.log', 'a') as log:
            log.write('Error: File already exists.')
    shutil.copy(file_name,directory)

for file in os.listdir(os.getcwd()):
    make_dir_with_file(file)

7

solved Copying a file and then printing the absolute path to its final destination [closed]