1.
File and Directory Management
Get the Current Working Directory
import os
print(os.getcwd()) # Returns the current working directory
Change the Current Working Directory
os.chdir('/path/to/directory') # Change to a specific directory
List Directory Contents
print(os.listdir('.')) # List all files and directories in the current directory
Create a Directory
os.mkdir('new_folder') # Create a single directory
os.makedirs('parent/child', exist_ok=True) # Create nested directories
Remove a Directory
os.rmdir('folder_name') # Remove an empty directory
os.removedirs('parent/child') # Remove nested empty directories
Rename Files or Directories
os.rename('old_name.txt', 'new_name.txt') # Rename a file or directory
2. Path Operations
The os.path module helps manipulate file paths.
Check if a Path Exists
os.path.exists('file_or_directory') # Returns True if the path exists
Check the Type of Path
os.path.isfile('file.txt') # Check if it's a file
os.path.isdir('directory') # Check if it's a directory
Get Absolute Path
os.path.abspath('file.txt') # Returns the absolute path of the file
Split Path
print(os.path.split('/path/to/file.txt')) # ('/path/to', 'file.txt')
Join Path Components
print(os.path.join('/path', 'to', 'file.txt')) # '/path/to/file.txt'
Get File Extension
print(os.path.splitext('file.txt')) # ('file', '.txt')
3. Environment Variables
Get Environment Variables
print(os.environ) # Get all environment variables
print(os.environ.get('HOME')) # Get the value of the 'HOME' variable
Set Environment Variables
os.environ['MY_VAR'] = 'value'
4. Process Management
Run System Commands
os.system('ls -la') # Run a shell command (use `subprocess` for advanced use
cases)
Get Process ID
print(os.getpid()) # Get the current process ID
print(os.getppid()) # Get the parent process ID
Exit the Program
os._exit(0) # Exit the program immediately
5. File Permissions and Metadata
Change Permissions
os.chmod('file.txt', 0o644) # Change file permissions
Check Ownership
print(os.stat('file.txt')) # Returns metadata such as size, owner, etc.
6. Cross-Platform Compatibility
The os library ensures code works across different operating systems (Linux, macOS,
Windows). For instance:
Detect the OS
print(os.name) # Returns 'posix', 'nt', etc., depending on the OS
Use Specific Directory Separator
print(os.sep) # '/' on POSIX systems and '\\' on Windows
Best Practices
Use the pathlib module (introduced in Python 3.4) for modern and object-oriented
path operations.
For running external commands, prefer the subprocess module over os.system.
Let me know if you'd like to explore specific functions in detail!
You said:
see content of the file using os library in python
ChatGPT said:
ChatGPT
The os library itself does not provide direct functions to read the content of a
file. Instead, it's typically used to navigate the filesystem and manage files
(e.g., opening, renaming, or deleting files). To read the content of a file, you
would use Python's built-in open() function. However, you can combine os with
open() to locate and read the content of a file.
Here's how you can do it:
Example: See the Content of a File
import os
# Specify the file path
file_path = 'example.txt'
# Check if the file exists
if os.path.exists(file_path) and os.path.isfile(file_path):
with open(file_path, 'r') as file:
content = file.read()
print(content)
else:
print(f"The file '{file_path}' does not exist or is not a file.")
Using os.listdir to Find Files in a Directory
If you don't know the exact file name but want to read all files in a directory:
import os
# Specify the directory path
directory = '.'
# List all files in the directory
for file_name in os.listdir(directory):
file_path = os.path.join(directory, file_name)
if os.path.isfile(file_path): # Check if it's a file
print(f"Contents of {file_name}:")
with open(file_path, 'r') as file:
print(file.read())
print("-" * 20) # Separator for readability
Points to Note
Use os.path.isfile to ensure you're opening a file and not a directory.
If you're working with large files, consider reading them line by line:
with open(file_path, 'r') as file:
for line in file:
print(line.strip())