user3245142
user3245142

Reputation: 81

Create directories based on filenames

I am an absolute beginner to programming so I apologize if this is really basic. I've looked at other questions that appear to be related, but haven't found a solution to this particular problem--at least not that I can understand.

I need to generate a list of files in a directory; create a separate directory for each of those files with the directory name being based on each file's name; and put each file in its corresponding directory.

Upvotes: 4

Views: 7727

Answers (2)

Steinar Lima
Steinar Lima

Reputation: 7821

You should have a look at the glob, os and shutil libraries.

I've written an example for you. This will remove the file extension of each file in a given folder, create a new subdirectory, and move the file into the corresponding folder, i.e.:

C:\Test\
 -> test1.txt
 -> test2.txt

will become

C:\Test\
 -> test1\
    -> test1.txt
 -> test2\
    -> test2.txt

Code:

import glob, os, shutil

folder = 'C:/Test/'

for file_path in glob.glob(os.path.join(folder, '*.*')):
    new_dir = file_path.rsplit('.', 1)[0]
    os.mkdir(os.path.join(folder, new_dir))
    shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))

This will throw an error if the folder already exist. To avoid that, handle the exception:

import glob, os, shutil

folder = 'C:/Test/'

for file_path in glob.glob(os.path.join(folder, '*.*')):
    new_dir = file_path.rsplit('.', 1)[0]
    try:
        os.mkdir(os.path.join(folder, new_dir))
    except WindowsError:
        # Handle the case where the target dir already exist.
        pass
    shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))

PS: This will not work for files without extensions. Consider using a more robust code for cases like that.

Upvotes: 9

user3553031
user3553031

Reputation: 6224

Here is some advice on listing files using Python.

To create a directory, use os.mkdir (docs). To move a file, use os.rename (docs) or shutil.move (docs).

Upvotes: 3

Related Questions