0% found this document useful (0 votes)
6 views1 page

Python File Handling Notes

This document provides a simple guide to Python file handling, covering operations such as opening, reading, writing, and renaming files. It emphasizes best practices using the 'with' statement and introduces exception handling to manage errors effectively. Key concepts include file modes, basic file operations, and structured error handling with try, except, else, and finally blocks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Python File Handling Notes

This document provides a simple guide to Python file handling, covering operations such as opening, reading, writing, and renaming files. It emphasizes best practices using the 'with' statement and introduces exception handling to manage errors effectively. Key concepts include file modes, basic file operations, and structured error handling with try, except, else, and finally blocks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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")

You might also like