DEV Community

Cover image for Using the os module for high-level file operations such as iterating, moving, copying, and deleting files and directories
Luca Liu
Luca Liu

Posted on โ€ข Edited on

Using the os module for high-level file operations such as iterating, moving, copying, and deleting files and directories

The os package in Python provides a wide range of functionalities for interacting with the operating system. One of the most commonly used aspects of this package is its ability to perform file and folder operations such as iteration, deletion, creation, moving, and opening. In this article, we'll explore how to utilize the os package for these tasks.

iterate through all the items within a folder

You can use the os package in Python to iterate through all the items within a folder using the os.listdir() method. And You can use the os.path.join function to concatenate the folder path with each item in the folder to get the absolute path. Here's an example of how to do it:

import os

# Replace 'folder_path' with the path of the folder you want to iterate through
folder_path = 'path_to_folder'

# Iterate through all items in the folder
for item in os.listdir(folder_path):
        print(item) 
        # Get the absolute path of the item
        item_path = os.path.join(folder_path, item) 
        # Display the absolute path of the item
        print(item_path)

Enter fullscreen mode Exit fullscreen mode

In this example, os.listdir(folder_path) returns a list of all the items (files and subfolders) in the specified folder. You can then iterate through this list and perform any operations you need for each item.

Remember to replace 'path_to_folder' with the actual path of the folder you want to iterate through.

Deleting Files and Folders

The os package provides methods to delete both files and folders. Here's how you can achieve this:

To delete a file:

import os
os.remove('file_path/file.txt')  # Replace with the actual file path
Enter fullscreen mode Exit fullscreen mode

To delete an empty folder:

import os
os.rmdir('folder_path')  # Replace with the actual folder path

Enter fullscreen mode Exit fullscreen mode

To delete a non-empty folder and all its contents:

import shutil
shutil.rmtree('folder_path')  # Replace with the actual folder path

Enter fullscreen mode Exit fullscreen mode

Remember to replace 'file_path/file.txt' and 'folder_path' with the actual paths of the file or folder you want to delete. Use these functions with caution as they will permanently delete the specified files or folders.

Creating Folders

Creating a new folder using the os package is straightforward:

import os
os.mkdir('new_folder')  # Replace with the desired folder name

Enter fullscreen mode Exit fullscreen mode

Moving and Renaming Files/Folders

The os package allows us to move and rename files and folders as well. Here's an example of moving a file:

import os
os.rename('old_location/file.txt', 'new_location/file.txt')

Enter fullscreen mode Exit fullscreen mode

Opening Files and Folders

You can also open a folder in the default file explorer using the os package. For instance, to open a folder in the File Explorer (Windows):

import os
os.startfile('folder_path')  # Replace with the actual folder path

Enter fullscreen mode Exit fullscreen mode

Conclusion

The os package in Python offers powerful capabilities for file and folder operations, allowing developers to efficiently manage file system tasks within their applications. By utilizing the methods provided by the os package, you can seamlessly iterate, delete, create, move, and open files and folders in your Python programs.


Explore more

Thank you for taking the time to explore data-related insights with me. I appreciate your engagement.

๐Ÿš€ Connect with me on LinkedIn

๐ŸŽƒ Connect with me on X

๐ŸŒ Connect with me on Instagram

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post โ†’

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up