Python project: files in folders are organized by file type

Table of Contents

Table of Contents

Development Environment

  • MacOS 11.2
$ python --version
Python 3.9.0

$ pyenv --version
pyenv 1.2.27

Goal

Here are some txt files and csv files in a folder as follows.

files/
  - txt1.txt
  - csv1.csv
  - txt2.txt
  - csv2.csv
  - txt3.txt
  - csv3.csv
  - txt4.txt
  - csv4.csv
  - txt5.txt
  - csv5.csv

I want to reorganize the files in the folder by file type.
And the final result will be this.

reorganization/
  - txt/
    - txt1.txt
    - txt2.txt
    - txt3.txt
    - txt4.txt
    - txt5.txt
  - csv/
    - csv1.csv
    - csv2.csv
    - csv3.csv
    - csv4.csv
    - csv5.csv

Let's Start

Workflow

  • Create a empty folder "reorganization".
  • Using loop function to process each file in the "files" folder.
  • In loop function, create a folder for that file type if it does not exist. Then copy the file into that folder.

Code

import os
import shutil

try:
    path = "./reorganization"
    if not(os.path.isdir(path)):
        os.mkdir(path)
    list = os.listdir("./files")
    for index, value in enumerate(list):
        (name, ext) = os.path.splitext(value)
        type_folder_path = f"{path}/{ext[1:]}"
        if not(os.path.isdir(type_folder_path)):
            os.mkdir(type_folder_path)
        shutil.copyfile(f"./files/{value}", f"{type_folder_path}/{value}")
        
except OSError:
    print (f"Failed" )
else:
    print (f"Success")

Module

  • os: check and create directory, and list files of the folder.
  • shutil: copy file.

Check and Create directory

use os.path.isdir() function to check if the folder exists or not.

path = "./reorganization"
if not(os.path.isdir(path)):
    os.mkdir(path)

Loop all files in the folder

use os.listdir() function to get the file list in the folder.

list = os.listdir("./files")
    for index, value in enumerate(list):
        #...

Get extension of file and Copy to target path

use os.path.splitext() funciton to get file's extension, and then use shutil.copyfile() to copy the file to target path.

for index, value in enumerate(list):
    (name, ext) = os.path.splitext(value)
    type_folder_path = f"{path}/{ext[1:]}"
    if not(os.path.isdir(type_folder_path)):
        os.mkdir(type_folder_path)
    shutil.copyfile(f"./files/{value}", f"{type_folder_path}/{value}")

Summary

  • use os.path.isdir() function to check if the folder exists or not.
  • use os.listdir() function to get the file list in the folder.
  • use os.path.splitext() funciton to get file's extension.
  • use shutil.copyfile() to copy the file to target path.