Python OS Module Tutorial 🎯

beginner
17 min

Python OS Module Tutorial 🎯

Welcome to the Python OS Module tutorial! In this lesson, we'll explore one of Python's built-in modules that allows us to interact with the operating system. Let's get started!

What is the OS Module? 📝

The os module in Python provides functionalities to interact with the underlying operating system. It's a powerful tool that helps you perform various tasks such as reading/writing files, manipulating directories, working with environment variables, and more.

Installing the OS Module ✅

Since the os module is a built-in module in Python, you don't need to install it separately. You can use it right away in your Python scripts!

Basic Usage 💡

Importing the OS Module

python
import os

Accessing Environment Variables

python
print(os.getenv('PYTHONPATH')) # prints the value of the PYTHONPATH environment variable

Working with Paths 📝

Getting the Current Working Directory

python
print(os.getcwd()) # prints the current working directory

Changing the Current Working Directory

python
os.chdir('/path/to/your/directory') # changes the current working directory

Checking if a Path Exists

python
if os.path.exists('/path/to/your/file'): print('File exists!')

Working with Files 💡

Listing all Files in a Directory

python
files = os.listdir('/path/to/your/directory') # returns a list of all files in the specified directory

Creating a New File

python
open('/path/to/new/file', 'w').close() # creates a new file named 'new_file' in the specified path

Removing a File

python
os.remove('/path/to/your/file') # removes the specified file

Working with Directories 💡

Creating a New Directory

python
os.mkdir('/path/to/new/directory') # creates a new directory named 'new_directory' in the specified path

Removing a Directory

python
os.rmdir('/path/to/your/directory') # removes the specified directory (only if it's empty)

Quiz

Quick Quiz
Question 1 of 1

Which function is used to list all files in a directory?

Conclusion 📝

In this tutorial, we learned about the os module in Python, which allows us to interact with the operating system. We covered basic usage, working with paths, files, and directories. With this knowledge, you can create more powerful and practical Python scripts!

Stay tuned for more Python tutorials, and remember to keep coding! 🚀