Project Level 2: Intermediate
This project is designed for intermediate learners who know Python fundamentals and are practicing building complete programs.
Project Objective
Create a Python script that organizes files in a directory into folders based on file type. For example, all .txt files go into a "Text Files" folder, all .jpg and .png files go into an "Images" folder, and so on.
How the Project Works
Here are what the script should do step by step:
Use
glob
to Find Files:Use the
glob
module to find all files in the target directory with specific patterns (like*.txt
for text files).
Create Folders Based on File Type:
For each file type, create a corresponding folder (e.g., "Text Files", "Images").
Move Files to the Appropriate Folder:
Move the files into the appropriate folder based on their extension using shutil.move().
Prerequisites
Required Libraries: No libraries are required.
Required Files: No files are required.
IDE: You can use any IDE on your computer to code the project.
Danger Zone
Once you code the project, compare it with our solution below:
import glob
import shutil as sh
import os
txt = r'C:\Users\GabrielDados\Desktop\TextFiles'
img = r'C:\Users\GabrielDados\Desktop\ImgFiles'
def make_directory(txt, img):
if not os.path.exists(txt):
os.mkdir(txt)
if not os.path.exists(img):
os.mkdir(img)
make_directory(txt, img)
def move_files():
files_txt = glob.glob(r'C:\Users\GabrielDados\Desktop\arquivos\**\*.txt', recursive=True)
files_png = glob.glob(r'C:\Users\GabrielDados\Desktop\arquivos\**\*.jpg', recursive=True)
files_jpg = glob.glob(r'C:\Users\GabrielDados\Desktop\arquivos\**\*.png', recursive=True)
for file in files_txt:
sh.move(file, r'C:\Users\GabrielDados\Desktop\TextFiles')
for file in (files_png):
sh.move(file, r'C:\Users\GabrielDados\Desktop\ImgFiles')
for file in (files_jpg):
sh.move(file, r'C:\Users\GabrielDados\Desktop\ImgFiles')
move_files()