List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Work with Directory in Python?

Work with Directory in Python

Condition for Work with Directory in Python

  • Description: A directory is a folder in a file system that holds files and other directories. In Python, working with directories involves performing operations such as creating, deleting, navigating, and listing files and directories.
Step-by-Step Process
  • os: The os module provides functions to interact with the operating system, including creating, deleting, and listing directories.
  • pathlib: The pathlib module provides an object-oriented approach to dealing with directories and paths. It is recommended over os for modern Python code.
  • Create a Directory: Use os.mkdir() or pathlib.Path.mkdir() to create a new directory in the specified location.
  • Change the Current Directory: Use os.chdir() to change the working directory, or pathlib.Path.cwd() to check the current directory and use chdir() for switching.
  • List Files in a Directory: Use os.listdir() to list all files and directories in the specified directory or pathlib.Path.iterdir() for an iterator over the contents.
  • Remove a Directory: Use os.rmdir() to remove an empty directory or pathlib.Path.rmdir() to remove the directory.
  • Check if a Directory Exists: Use os.path.exists() or pathlib.Path.exists() to check if a specific directory exists.
Sample Code
  • import os
    from pathlib import Path
    # Create a Directory
    os.mkdir('example_dir')
    print("Directory 'example_dir' created using os.")
    print()
    # Check if the Directory Exists
    path = Path('example_dir')
    if path.exists():
      print("Directory 'example_dir' exists.")
    else:
      print("Directory 'example_dir' does not exist.")
    print()
    # List Files in a Directory
    print("Contents of the current directory using os:", os.listdir('.'))
    print()
    # Change the Current Directory
    os.chdir('example_dir')
    print(f"Current directory after change: {os.getcwd()}")
    print()
    # Write to a File in the Directory
    with open('example_file.txt', 'w') as file:
      file.write("Hello, this is a test file inside the 'example_dir'.")
    print("File 'example_file.txt' created and content written.")
    print()
    # Read the File to Check the Content
    with open('example_file.txt', 'r') as file:
      content = file.read()
      print("======Text inside the file======")
      print("Content of the file:", content)
    print()
    # Remove the File Before Removing the Directory
    file_path = Path('example_file.txt')
    if file_path.exists():
      file_path.unlink() # Remove the file
      print("File 'example_file.txt' removed.")
    print()
    # Remove the Directory
    os.chdir('..')
    path.rmdir()
    print("======After removing:====")
    print("Directory 'example_dir' removed using pathlib.")
Screenshots
  • Work with Directory