HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Group and send all files to filetype folder

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
groupallfilesfiletypefolderandsend

Problem

I have around ~2M of files in one folder, which I need to manage. So, I want to separate them in groups by their filetypes.

Example:

filenames

1.A, 2.A, 3.A, 2.B, 3.B, 4.B, 5.C, 6.C


My code:

import os
all_files = os.listdir(".")
filetypes = list(set([i.split(".")[-1] for i in all_files]))
for i in filetypes:
    os.system("mkdir -p %s"%i)
    os.system("mv *.%s %s"%(i, i))


How can I improve this?

Solution

Avoid os.system() by all means. It wastes resources by creating 2 processes per invocation, and is vulnerable to various attacks (at least spell out full paths to the mkdir and mv utilities).

os.mkdir() provide all necessary functionality (don't forget to catch OSError). A combination of os.link() and os.unlink() emulates mv (they are only available on Unix - but you are calling mv anyway).

Context

StackExchange Code Review Q#60350, answer score: 5

Revisions (0)

No revisions yet.