Python os
Package: Overview and Examples
The os
package in Python provides a way of using operating system-dependent functionality like reading or writing to the file system. This module provides a portable way of using operating system-dependent functionalities and is a part of the standard library.
Importing the os
Module
To use the os
module, you first need to import it.
Commonly Used Functions
Working with Directories
os.getcwd()
Returns the current working directory.
os.listdir()
Returns a list of entries in the specified directory.
os.mkdir()
Creates a new directory.
os.makedirs()
Creates a new directory and any necessary parent directories.
os.rmdir()
Removes an empty directory.
os.removedirs()
Removes directories recursively.
os.chdir()
Changes the current working directory.
Working with Files
os.rename()
Renames a file or directory.
os.remove()
Removes a file.
Environment Variables
os.environ
A mapping object representing the string environment.
os.getenv()
Gets the value of an environment variable.
os.putenv()
Sets the value of an environment variable.
Path Manipulations
os.path.join()
Joins one or more path components intelligently.
os.path.exists()
Returns True
if the path exists.
os.path.isfile()
Returns True
if the path is a regular file.
os.path.isdir()
Returns True
if the path is a directory.
os.path.getsize()
Returns the size of the file in bytes.
os.path.abspath()
Returns the absolute path of the specified path.
Example: Creating a Directory, Writing a File, and Cleaning Up
import os
# Create a new directory
os.mkdir('example_dir')
# Change to the new directory
os.chdir('example_dir')
# Create and write to a new file
with open('example_file.txt', 'w') as file:
file.write('Hello, world!')
# Read the file
with open('example_file.txt', 'r') as file:
content = file.read()
print(content)
# Change back to the parent directory
os.chdir('..')
# Remove the file and directory
os.remove('example_dir/example_file.txt')
os.rmdir('example_dir')
Conclusion
The os
package in Python is a powerful tool for interacting with the operating system. It provides functionalities for directory and file operations, environment variables, and path manipulations. Understanding and utilizing these functions can significantly enhance your ability to manage files and directories programmatically.