p>
Learning Sections show
Learning Sections show
os Module in Python
1. Working with Directories
You can perform various directory-related operations using the os
module.
import os
# Get current working directory
cwd = os.getcwd()
print(cwd)
# Change directory
os.chdir("/path/to/directory")
# List directory contents
files = os.listdir('.')
print(files)
2. File Operations
The os
module also allows you to perform file operations such as creating, removing, and renaming files.
# Create a new file
with open('test.txt', 'w') as f:
f.write('Hello, world!')
# Rename the file
os.rename('test.txt', 'new_test.txt')
# Remove the file
os.remove('new_test.txt')
3. Environment Variables
You can access and manipulate environment variables using the os
module.
# Get an environment variable
home_dir = os.environ.get('HOME')
print(home_dir)
# Set an environment variable
os.environ['MY_VAR'] = 'my_value'
4. Path Manipulation
The os.path
submodule provides functions for working with file and directory paths.
import os.path as path
# Check if a path exists
path_exists = path.exists('/path/to/file')
print(path_exists)
# Join paths
full_path = path.join('/path/to', 'file.txt')
print(full_path)
# Get the directory name
dir_name = path.dirname('/path/to/file.txt')
print(dir_name)