Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

How to use Python os module

The os module is a built-in Python module that provides a way to interact with the operating system. It includes various functions related to directory operations, permissions, and file access. Here is a brief overview of some of the commonly used functions in each category:

Directory related functions

os.getcwd()

This function returns the current working directory as a string.

Example usage:

import os

cwd = os.getcwd()
print(cwd)

os.chdir(path)

This function changes the current working directory to the one specified by the path argument.

Example usage:

import os

os.chdir('/path/to/new/directory')

os.listdir(path='.')

This function returns a list of all files and directories in the directory specified by the path argument. If no argument is provided, it returns the contents of the current working directory.

Example usage:

import os

files_and_dirs = os.listdir('/path/to/directory')
print(files_and_dirs)

os.mkdir(path[, mode=0o777[, *, dir_fd=None]])

This function creates a new directory with the name specified by the path argument. It also takes an optional mode argument that specifies the permissions for the new directory.

Example usage:

import os

os.mkdir('/path/to/new/directory')

Permission related functions

os.chmod(path, mode)

This function changes the permissions of the file or directory specified by the path argument to the permissions specified by the mode argument.

Example usage:

import os

os.chmod('/path/to/file', 0o777)

os.access(path, mode)

This function checks whether the current user has the specified mode permissions for the file or directory specified by the path argument.

Example usage:

import os

if os.access('/path/to/file', os.R_OK):
    print('File is readable')
else:
    print('File is not readable')

File access related functions

os.rename(src, dst)

This function renames the file or directory specified by the src argument to the new name specified by the dst argument.

Example usage:

import os

os.rename('/path/to/old/file', '/path/to/new/file')

os.remove(path)

This function deletes the file specified by the path argument.

Example usage:

import os

os.remove('/path/to/file')

os.path.isfile(path)

This function returns True if the file specified by the path argument exists and is a file.

Example usage:

import os

if os.path.isfile('/path/to/file'):
    print('File exists')
else:
    print('File does not exist')

os.path.isdir(path)

This function returns True if the directory specified by the path argument exists and is a directory.

Example usage:

import os

if os.path.isdir('/path/to/directory'):
    print('Directory exists')
else:
    print('Directory does not exist')
  1. Working with directories in Python using os module:

    • Description: The os module provides functions for working with directories, such as creating, removing, and listing directories.
    • Code:
      import os
      
      # Get the current working directory
      current_directory = os.getcwd()
      
      # List files and directories in the current directory
      file_list = os.listdir(current_directory)
      
      # Create a new directory
      new_directory = os.path.join(current_directory, "new_folder")
      os.makedirs(new_directory)
      
      # Remove a directory
      os.rmdir(new_directory)
      
  2. File and path manipulation with os module in Python:

    • Description: Use various os module functions for file and path manipulation, such as joining paths, splitting paths, and getting the basename.
    • Code:
      import os
      
      file_path = "/path/to/example.txt"
      
      # Extract directory and filename from the path
      directory, filename = os.path.split(file_path)
      
      # Join paths
      new_path = os.path.join(directory, "new_folder", filename)
      
      # Get the absolute path
      absolute_path = os.path.abspath(file_path)
      
  3. Using os.environ for environment variables in Python:

    • Description: Access and modify environment variables using os.environ.
    • Code:
      import os
      
      # Get the value of the HOME environment variable
      home_directory = os.environ.get("HOME")
      
      # Set a new environment variable
      os.environ["MY_VARIABLE"] = "my_value"
      
  4. Executing shell commands with os.system in Python:

    • Description: Run shell commands using os.system.
    • Code:
      import os
      
      # Execute a shell command
      os.system("echo Hello, World!")
      
  5. Getting current working directory with os.getcwd() in Python:

    • Description: Use os.getcwd() to get the current working directory.
    • Code:
      import os
      
      # Get the current working directory
      current_directory = os.getcwd()
      
  6. Listing files and directories with os.listdir() in Python:

    • Description: Use os.listdir() to get a list of files and directories in a given path.
    • Code:
      import os
      
      directory_path = "/path/to/folder"
      
      # List files and directories
      contents = os.listdir(directory_path)
      
  7. Creating and removing directories with os.makedirs() and os.rmdir() in Python:

    • Description: Use os.makedirs() to create directories recursively and os.rmdir() to remove an empty directory.
    • Code:
      import os
      
      # Create a new directory
      os.makedirs("/path/to/new_folder")
      
      # Remove an empty directory
      os.rmdir("/path/to/new_folder")
      
  8. Checking file existence with os.path.exists() in Python:

    • Description: Use os.path.exists() to check whether a file or directory exists at a given path.
    • Code:
      import os
      
      file_path = "/path/to/example.txt"
      
      # Check if the file exists
      if os.path.exists(file_path):
          print("File exists!")
      else:
          print("File does not exist.")
      
  9. File and directory permissions with os.chmod() in Python:

    • Description: Change file or directory permissions using os.chmod().
    • Code:
      import os
      
      file_path = "/path/to/example.txt"
      
      # Set read and write permissions for the owner
      os.chmod(file_path, 0o600)
      
  10. Platform-independent path handling with os.path.join() in Python:

    • Description: Use os.path.join() for platform-independent path handling, creating paths by joining components.
    • Code:
      import os
      
      folder = "path"
      file_name = "example.txt"
      
      # Join paths
      full_path = os.path.join(folder, file_name)
      
  11. Changing the current working directory with os.chdir() in Python:

    • Description: Use os.chdir() to change the current working directory.
    • Code:
      import os
      
      new_directory = "/new/path"
      
      # Change the current working directory
      os.chdir(new_directory)
      
  12. Running external processes with subprocess and os in Python:

    • Description: Use the subprocess module to run external processes with more control than os.system().
    • Code:
      import subprocess
      
      # Run an external command and capture output
      result = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE, text=True)
      print(result.stdout)
      
  13. Handling file paths and separators with os.path module in Python:

    • Description: Use os.path module functions, such as os.path.sep and os.path.join, for cross-platform file path handling.
    • Code:
      import os
      
      # Get the platform-specific path separator
      separator = os.path.sep
      
      # Join paths using os.path.join
      full_path = os.path.join("folder", "file.txt")