Create Separate Folders Based on Files Prefix And Copy Them Accordingly

Question:

I have a set of files ranging like this:

Doc0001-done.xlsx,
Doc0001-status.xlsx,
Doc0001-pending.xlsx,

Doc0002-done.xlsx,
Doc0002-status.xlsx,
Doc0002-pending.xlsx,

Doc0483-done.xlsx,
Doc0483-status.xlsx,
Doc0483-pending.xlsx,

How can I write a script to help me create a separate folder for each prefix and then copy the files accordingly, like create a Folder for Doc0001 and copy the done, status and pending there, and so on with the other prefixes. There are too many, it would take me an eternity. Really thank you in advance.

Asked By: Erghi

||

Answers:

import os
from shutil import copyfile
path_to_files = '/Users/path_to_dir_with_files'
files = os.listdir(path_to_files)
for file in files:
    if file.startswith('Doc'):
        _dir = file[:file.find('-')]
        if _dir not in os.listdir(path_to_files):
            os.mkdir(_dir)
        copyfile(f'{path_to_files}/{file}', f'{path_to_files}/{_dir}/{file}')
Answered By: bilannnn

You can a brace expansion with a pathname expansion. To make the folders you do.

mkdir Doc{0001..0483}

Where Doc{0001..0483} is a brace expansion which expands to Doc0001 Doc0002 … Doc0483.
To move the files to the folder you would do

for x in Doc{0001..0483}; do mv $x* $x; done

where * corresponds to pathname expansion which expands to all the files beginning with $x (note pathname expansion happens after parameter expansion which makes this possible).

Answered By: Progamer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.