Python File Handling, Operations & Exception Handling
(Simple Guide)
1. What is File Handling?
File handling means working with files (reading, writing, updating) using Python.
2. Opening a File
Use open() function: open('[Link]', 'r')
File Modes
r = read w = write (overwrites) a = append x = create new file
3. Reading a File
file = open('[Link]', 'r') print([Link]()) [Link]()
4. Writing to a File
file = open('[Link]', 'w') [Link]('Hello') [Link]()
5. Using 'with' (Best Practice)
with open('[Link]', 'r') as file: print([Link]())
6. File Operations
Rename: [Link]('[Link]', '[Link]') Delete: [Link]('[Link]')
7. Exception Handling
Used to handle errors without crashing program.
Basic Example
try: x = int(input()) except: print('Error!')
Types
try - test code except - handle error else - runs if no error finally - always runs
Example with all
try: num = int(input("Enter number: ")) except ValueError: print("Invalid input") else: print("Good
input") finally: print("Done")