GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python OS Module - Operating System Utilities Python OS Modulelast modified February 15, 2025
In this article, we show how to use the
The Navigating the File System
The following example demonstrates how to use the main.py
import os
# Get the current working directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)
# Change the current working directory
os.chdir('/tmp')
print("Changed Directory:", os.getcwd())
# List files and directories in the current directory
print("Files and Directories:", os.listdir())
In this program, the Working with Files and Directories
The following example demonstrates how to create, rename, and delete files and
directories using the main.py
import os
# Create a new directory
os.mkdir('new_directory')
print("Directory Created:", 'new_directory')
# Rename the directory
os.rename('new_directory', 'renamed_directory')
print("Directory Renamed:", 'renamed_directory')
# Create a new file
with open('new_file.txt', 'w') as f:
f.write('Hello, World!')
print("File Created:", 'new_file.txt')
# Delete the file
os.remove('new_file.txt')
print("File Deleted:", 'new_file.txt')
# Delete the directory
os.rmdir('renamed_directory')
print("Directory Deleted:", 'renamed_directory')
In this program, the $ python main.py Directory Created: new_directory Directory Renamed: renamed_directory File Created: new_file.txt File Deleted: new_file.txt Directory Deleted: renamed_directory Environment Variables
The following example demonstrates how to work with environment variables using
the main.py
import os
# Get the value of an environment variable
home_directory = os.getenv('HOME')
print("Home Directory:", home_directory)
# Set a new environment variable
os.environ['MY_VAR'] = 'my_value'
print("MY_VAR:", os.getenv('MY_VAR'))
# List all environment variables
print("Environment Variables:", os.environ)
In this program, the Running System Commands
The following example demonstrates how to run system commands using the
main.py
import os
# Run a system command
os.system('ls -l')
In this program, the Path Manipulation with os.path
The following example demonstrates how to manipulate file paths using the
main.py
import os
# Join path components
path = os.path.join('/home', 'user', 'documents', 'file.txt')
print("Joined Path:", path)
# Get the basename of the path
basename = os.path.basename(path)
print("Basename:", basename)
# Get the directory name of the path
dirname = os.path.dirname(path)
print("Dirname:", dirname)
# Check if the path exists
exists = os.path.exists(path)
print("Path Exists:", exists)
In this program, the Rename a File with os.rename
The following example demonstrates how to rename a file using the main.py
import os
# Specify the file name
file_name = 'myfile.txt'
# Check if the file exists
if os.path.exists(file_name):
# Rename the file
os.rename('myfile.txt', 'myfile2.txt')
print("File renamed successfully.")
else:
print('Failed to rename file: File does not exist.')
In this program, the $ python main.py File renamed successfully. If the file does not exist, the program will output: $ python main.py Failed to rename file: File does not exist. List Directory with os.listdir
The following example demonstrates how to list the contents of a directory using
the main.py
import os
# List all entries in the current directory
content = os.listdir('.')
print("Directory Contents:", content)
In this program, the List Directory with os.scandir
The following example demonstrates how to list the contents of a directory using the main.py
import os
from datetime import datetime
# Specify the directory path
path = '.'
# Use scandir to list entries with additional info
with os.scandir(path) as it:
for entry in it:
print(f'{entry.name} - Created: {datetime.fromtimestamp(entry.stat().st_ctime)}')
In this program, the Traverse Directory with os.walk
The following example demonstrates how to traverse a directory recursively using
the main.py
import os
# Traverse the directory tree starting from the current directory
for root, dirs, files in os.walk(os.path.abspath(".")):
# Print all files in the current directory
for name in files:
print(os.path.join(root, name))
# Print all subdirectories in the current directory
for name in dirs:
print(os.path.join(root, name))
In this program, the
The SourcePython OS Module - Documentation
In this article, we have shown how to use the AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |