Welcome to the File Organizer project tutorial! In this lesson, you'll learn Python basics by building a simple file organizer application.
By the end of this project, you'll have a practical understanding of essential Python concepts, including:
Before diving in, let's ensure you have the following prerequisites:
Our goal is to create a command-line application that helps users organize their files by moving them to their respective directories based on file extensions. For instance, moving .txt files to a text_files directory and .jpg files to an images directory.
Variables are used to store data in your program. Here's an example:
my_variable = "Hello, World!"
print(my_variable)Python has various data types, including:
string (immutable sequence of characters)integer (whole numbers)float (decimal numbers)boolean (True/False values)list (ordered, mutable collection of items)tuple (ordered, immutable collection of items)dictionary (unordered collection of key-value pairs)Let's read the files in our current directory:
import os
files = os.listdir()
print(files)And let's create a new file:
open("new_file.txt", "w").close()Conditional statements allow your code to make decisions. Here's an example using an if statement:
file_extension = "txt"
if file_extension == "txt":
print("This is a text file.")Loops allow you to repeat blocks of code. We'll use a for loop to move files to their respective directories:
source_directory = "."
destination_directories = {"txt": "text_files", "jpg": "images"}
for file in os.listdir(source_directory):
extension = file.split(".")[-1]
if extension in destination_directories:
destination_path = os.path.join(source_directory, destination_directories[extension])
source_path = os.path.join(source_directory, file)
os.rename(source_path, os.path.join(destination_path, file))Functions help organize your code and make it more readable. Here's an example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")List comprehensions are a concise way to create lists. Here's an example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers)Now that you've learned the basics, let's put everything together to build our file organizer.
What does the `os.listdir()` function do?
What is the purpose of the `os.path.join()` function?
How do we move a file using Python?