The os module in Python provides functions for interacting with the operating system in a way that is cross-platform. You can use it to perform many different types of operating system-related operations.
Here’s how you might use the os module:
1. Importing the module:
To use the os module, you will first need to import it. This is done with the `import` keyword.
```
import os
```
1. Using Functions and properties:
Here are a few examples of os functions and properties:
- `os.name`: It returns the name of the operating system dependent module imported.
```
print(os.name) # nt (Windows), posix (Linux, Mac), java (Jython)
```
- `os.getcwd()`: Returns the current working directory.
```
print(os.getcwd()) # Outputs ‘/home/user/my_documents/python‘
```
- `os.chdir()`: Change the current working directory to the specified path.
```
os.chdir(‘/home/user/my_documents’)
print(os.getcwd()) # Outputs ‘/home/user/my_documents‘
```
- `os.listdir()`: Returns a list of all files and directories in the specified directory.
```
print(os.listdir()) # Outputs [‘file1.txt’, ‘file2.txt’, ‘dir1’, ‘dir2’]
```
- `os.mkdir()`: Create a directory.
```
os.mkdir(‘new_dir’)
print(os.listdir()) # Outputs [‘file1.txt’, ‘file2.txt’, ‘dir1’, ‘dir2’, ‘new_dir’]
```
- `os.rename()`: Rename a file or a directory.
```
os.rename(‘new_dir’, ‘old_dir’)
print(os.listdir()) # Outputs [‘file1.txt’, ‘file2.txt’, ‘dir1’, ‘dir2’, ‘old_dir’]
```
- `os.remove()`: Remove (delete) a file.
```
os.remove(‘file1.txt’)
print(os.listdir()) # Outputs [‘file2.txt’, ‘dir1’, ‘dir2’, ‘old_dir’]
```
- `os.rmdir()`: Remove (delete) an empty directory.
```
os.rmdir(‘old_dir’)
print(os.listdir()) # Outputs [‘file2.txt’, ‘dir1’, ‘dir2’]
```
It has many other functionalities that you can check out in the Python docs: https://docs.python.org/3/library/os.html