prev
next
Or press ESC to close.
To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content. To continue enjoying our content, please consider disabling your ad blocker. Your support helps us continue providing quality content.

Python Programming Part 17

Rajjit Nov 09th, 2023 10 mins read
part-17

TOPIC: Python File Methods and Directory Methods

File Methods

  • rename() method
    The rename() method in Python is a function used to change the name of a file or directory. It's part of the os module, providing an interface to the operating system's functionality. This method can be used not only to rename a file but also to move it to a different directory while changing its name simultaneously.

    Example of renaming a file:

    import os
    # Renaming a file from "old_file.txt" to "new_file.txt"
    os.rename("old_file.txt", "new_file.txt")

    Example of moving and renaming:

    import os
    # Renaming and moving a file from "folder1/old_file.txt" to "folder2/new_file.txt"
    os.rename("folder1/old_file.txt", "folder2/new_file.txt")
    
    The rename() method in Python's os module is a versatile function allowing you to change the names of files or directories and move them to different locations. However, proper error handling should be implemented to manage potential exceptions during the renaming process.
  • remove() method
    The remove() method in Python is used to delete or remove a file. It's part of the os module and allows you to delete a file by providing its filename as an argument.

    Example of removing a file:

    import os
    # Removing a file named "unwanted_file.txt"
    os.remove("unwanted_file.txt")
    
    The remove() method provides a straightforward way to delete files from the filesystem, but it's crucial to handle potential exceptions and ensure necessary permissions for successful file deletion.

Directory Methods

  • mkdir() method
    The mkdir() method in Python's os module is used to create a new directory or folder. It allows you to create a directory by specifying its name or path. The os.mkdir() method creates a new directory with the specified name. If the directory already exists or the specified path is invalid, an exception will be raised.

    Example of creating a directory or folder:

    import os
    # Creating a nested directory structure "parent_dir/sub_dir"
    os.mkdir("parent_dir/sub_dir")
    
  • getcwd() method
    The getcwd() method in Python's os module is used to get the current working directory. It returns a string representing the current working directory where the Python script is executing.

    Example of getting the current working directory:

    import os
    # Get the current working directory
    current_directory = os.getcwd()
    print("Current Working Directory:", current_directory)
    

    The returned path from getcwd() can be used for various purposes, such as accessing files, navigating directories, or verifying the script's location.

  • chdir() method
    The chdir() method in Python's os module is used to change the current working directory to the specified path. It allows you to navigate to a different directory within the filesystem.

    Example of changing the current working directory:

    import os
    # Change the current working directory to "new_directory"
    os.chdir("new_directory")
    

    Example of navigating to different directories:

    import os
    # Change the directory path
    new_path = "/path/to/directory"
    os.chdir(new_path)
    
  • rmdir() method
    The rmdir() method in Python's os module is used to remove or delete an empty directory. It's specifically designed to delete directories that don't contain any files or subdirectories.

    Example of removing an empty directory:

    import os
    # Remove an empty directory named "empty_dir"
    os.rmdir("empty_dir")
    

    Limitation of rmdir() method is that it can only delete empty directories. If the directory contains files or subdirectories, it will raise an OSError. In order to remove the directory containing contents, we will use other modules. For that part, we are going to discuss in the upcoming videos and blog.

  • makedirs() method
    The makedirs() method in Python's os module is used to create a directory or a series of nested directories. It allows the creation of parent directories along with the specified directory, if they do not already exist.

    Example of creating directories:

    import os
    # Create a directory "new_directory"
    os.makedirs("new_directory")
    

    It can create a hierarchy of directories by specifying a path with multiple directory names separated by the path separator (e.g., / or \).
    Example of creating nested directories:

    import os
    # Create nested directories "parent_dir/sub_dir"
    os.makedirs("parent_dir/sub_dir")
    

    In Python, the double forward slash // is commonly used as a path separator on Windows systems. THe explanation of the topic is discussed in the video. Example:

    import os
    # Create nested directories "parent_dir//sub_dir" using //
    os.makedirs("parent_dir//sub_dir")
    

Code as discussed in the video:

# Python File methods and Directory methods

# File methods - rename()
# syntax - 
#     os.rename(old_filename, new_filename)

import os
# os.rename('tutorial15.txt', 'tut15.txt')
# print("File renamed")

# remove()
# syntax -
#     os.remove(Filename)
# os.remove('testfile.txt')

# Directory method - mkdir()
# syntax - 
#     os.mkdir(folder_name)
# os.mkdir('project')
# os.rename('project/project1.txt', 'project/newProject.txt')

#  getcwd()
# syntax - 
    # os.getcwd()
# print(os.getcwd())

# chdir()
# syntax - 
#     os.chdir("dirname")
# os.chdir("project")
# print(os.getcwd())

# rmdir()
# syntax -
#     os.rmdir("dirname")

# os.rmdir("project") # if not empty, it will give error

# makedirs()
# syntax -
# os.makedirs("ndir1\\ndir2\\ndir3\\ndir4")

# Extra
os.startfile("C:\\Windows\\explorer.exe")

You can copy and run this code