I/O handling (File input output, reading and writing back to files
# Opening a file
file = open("file_name", "mode")
# mode determines how the file will be opened
'''
'r' -> read mode (default)
'w' -> write mode (overwrites file with new data)
'a' -> append mode (adds new data to end of the file)
'b' -> binary mode (for binary files)
'''
-----------------------------------------------------------------------
# To read the content of the file
content = file.read()
# read line by line
content = file.readline()
# read lines in a list
content = file.readlines()
-----------------------------------------------------------------------
# Writing to a file
file.write('Text goes here')
# write multiple lines
file.writelines(['Hello', 'world'])
-----------------------------------------------------------------------
# Always close file, to free up system resources
file.close()
-----------------------------------------------------------------------
# This simplifies exception handling by encapsulating common tasks in context-managers
# Context Managers - automatically handles file closing)
with open('file_name', 'mode') as file:
content = file.read()
-----------------------------------------------------------------------
# handling file paths
# The os and pathlib modules provide methods to handle file paths.
# pathlib is more modern and object-oriented.
from pathlib import Path
p = Path('/path/to/file')
with p.open('r') as file:
content = file.read()
-----------------------------------------------------------------------
# working with binary files
# When dealing with binary files, you append 'b' to the mode in open().
with open('filename', 'rb') as file:
binary_data = file.read()
-----------------------------------------------------------------------
# Error handling
# Good practice to handle potential error that may occur during file operation
try:
with ("file_name", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
except Exception as e:
print('An error occurred:', e)
# Advanced Topics:
File encoding and decoding
Processing files in chunks for memory efficiency
Using file operations with networked files or databases
*args, **kwargs
def print_name(*args)
Advanced