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)
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:
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')
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')
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')
Working with directories in Python using os module:
os
module provides functions for working with directories, such as creating, removing, and listing directories.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)
File and path manipulation with os module in Python:
os
module functions for file and path manipulation, such as joining paths, splitting paths, and getting the basename.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)
Using os.environ for environment variables in Python:
os.environ
.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"
Executing shell commands with os.system in Python:
os.system
.import os # Execute a shell command os.system("echo Hello, World!")
Getting current working directory with os.getcwd() in Python:
os.getcwd()
to get the current working directory.import os # Get the current working directory current_directory = os.getcwd()
Listing files and directories with os.listdir() in Python:
os.listdir()
to get a list of files and directories in a given path.import os directory_path = "/path/to/folder" # List files and directories contents = os.listdir(directory_path)
Creating and removing directories with os.makedirs() and os.rmdir() in Python:
os.makedirs()
to create directories recursively and os.rmdir()
to remove an empty directory.import os # Create a new directory os.makedirs("/path/to/new_folder") # Remove an empty directory os.rmdir("/path/to/new_folder")
Checking file existence with os.path.exists() in Python:
os.path.exists()
to check whether a file or directory exists at a given path.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.")
File and directory permissions with os.chmod() in Python:
os.chmod()
.import os file_path = "/path/to/example.txt" # Set read and write permissions for the owner os.chmod(file_path, 0o600)
Platform-independent path handling with os.path.join() in Python:
os.path.join()
for platform-independent path handling, creating paths by joining components.import os folder = "path" file_name = "example.txt" # Join paths full_path = os.path.join(folder, file_name)
Changing the current working directory with os.chdir() in Python:
os.chdir()
to change the current working directory.import os new_directory = "/new/path" # Change the current working directory os.chdir(new_directory)
Running external processes with subprocess and os in Python:
subprocess
module to run external processes with more control than os.system()
.import subprocess # Run an external command and capture output result = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE, text=True) print(result.stdout)
Handling file paths and separators with os.path module in Python:
os.path
module functions, such as os.path.sep
and os.path.join
, for cross-platform file path handling.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")