DEV Community

Discussion on: Python script for Sorting Files w.r.t Filetype Extensions

Collapse
 
voyeg3r profile image
Info Comment hidden by post author - thread only visible in this permalink
Sérgio Araújo • Edited

I am thinking of how to create a more generic method and apply a kind of decorator to perform this action, but for now, it is just an idea.

I think the first step is to get the varible names to transform them, like documents to DocumentsLocation. In python 3 to get the variable name we can do: f'{documents=}'.split('=')[0]

I have already done this: variable = f'{x=}'.split('=')[0].title() + 'Location'
some research here: stackoverflow.com/a/58451182/2571881

In fact I have done this:

#!/usr/bin/env python
# coding: utf-8

from pathlib import Path
downloads = Path.home() / 'Downloads/'

for f in downloads.iterdir():
    if f.is_file():
        name, ext = f.name, f.suffix[1:]
        p = Path(downloads) / f'{ext}_files'
        p.mkdir(parents=True, exist_ok=True)
        Path(f).rename(p / f'{f.name}')

With a little StackOverflow help: stackoverflow.com/a/52774612
It can be improved to separate file families but for now what it does is: It creates folders like:

mp3_files, doc_files, iso_files and so on

Another idea is to use python to get file metadata an read the type from the files itselves. Today I have found this:

>>> import mimetypes
>>> import os
>>> for f in os.listdir('.'):
...     print(mimetypes.guess_type(f))
...

Some comments have been hidden by the post's author - find out more