Python OS Module Guide

The OS module is a built-in module in Python that allows interaction with the operating system. Here are some common examples of using the OS module:

  1. Get the current working directory.
import os

current_dir = os.getcwd()
print(current_dir)
  1. Create a folder:
import os

os.mkdir("new_directory")
  1. Remove directory.
import os

os.rmdir("directory_to_delete")
  1. List the files and subdirectories in the directory.
import os

contents = os.listdir("directory_path")
for item in contents:
    print(item)
  1. Check if the file or directory exists:
import os

exists = os.path.exists("file_or_directory_path")
if exists:
    print("File or directory exists!")
else:
    print("File or directory does not exist!")
  1. Execute operating system command:
import os

os.system("command_to_execute")

This is just a small example of the functions of the OS module, there are other functions such as file operations, path operations, environment variables, and more. You can refer to the official Python documentation or other tutorials for more ways to use it.

bannerAds