0% found this document useful (0 votes)
5 views

File Handling Notes Updated

This document provides an overview of file handling in Python, detailing built-in functions for creating, reading, updating, and deleting files. It covers various file modes, methods for reading and writing files, and the use of the 'with' statement for resource management. Additionally, it includes practical exercises and examples for handling text and binary files, along with exception handling techniques.
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)
5 views

File Handling Notes Updated

This document provides an overview of file handling in Python, detailing built-in functions for creating, reading, updating, and deleting files. It covers various file modes, methods for reading and writing files, and the use of the 'with' statement for resource management. Additionally, it includes practical exercises and examples for handling text and binary files, along with exception handling techniques.
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
You are on page 1/ 3

File Handling in Python

This notebook provides an overview of file handling in Python with explanations and examples.

1. Introduction to File Handling


File handling is an essential part of programming. Python provides built-in functions for creating, reading,
updating, and deleting files. It supports various file types, including text files and binary files.

2. File Modes
The different file modes in Python are:

'r' : Read mode (default). Opens a file for reading.


'w' : Write mode. Opens a file for writing (overwrites if the file exists).
'a' : Append mode. Opens a file for appending content.
'b' : Binary mode. Used with other modes for binary files (e.g., 'rb' , 'wb' ).
'x' : Exclusive creation mode. Fails if the file exists.
'+' : Read and write mode (e.g., 'r+' , 'w+' ).

3. Reading Files
You can use the following methods to read files in Python:

In [ ]: # Example: Reading a file using read()


with open('example.txt', 'r') as file:
content = file.read()
print(content)

In [ ]: # Example: Reading line by line using readline()


with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()

In [ ]: # Example: Reading all lines using readlines()


with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line, end='')

4. Writing to Files
You can write to files using the 'w' mode. Be cautious as it overwrites existing content.

In [ ]: # Example: Writing to a file


with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is a new line.')

5. Appending to Files
Use the 'a' mode to append content to a file without overwriting existing data.

In [ ]: # Example: Appending to a file


with open('example.txt', 'a') as file:
file.write('\nAppending a new line.')

6. Using with Statement


The with statement is used to manage file resources efficiently. It ensures files are properly closed after
operations.

In [ ]: # Example: Using 'with' to handle files


with open('example.txt', 'r') as file:
print(file.read())

7. Handling Binary Files


Binary files (e.g., images, audio files) can be handled using the 'b' mode.

In [ ]: # Example: Reading a binary file


with open('image.jpg', 'rb') as file:
binary_content = file.read()
print(binary_content[:10]) # Print first 10 bytes

8. File Handling Exceptions


Use try-except blocks to handle file-related exceptions gracefully.

In [ ]: # Example: Handling exceptions in file operations


try:
with open('non_existent_file.txt', 'r') as file:
print(file.read())
except FileNotFoundError:
print('File not found!')
except Exception as e:
print(f'An error occurred: {e}')

9. Practical Exercises
1. Write a Python program to count the number of lines in a text file.
2. Create a program that reads a file and prints all lines that contain the word 'Python'.
3. Write a script to copy the contents of one file to another.
4. Develop a program to read and write binary files, such as copying an image.

In [ ]: # Example 1: Reading a file using read()


with open('example.txt', 'r') as file:
content = file.read()
print(content)

In [ ]: # Example 2: Reading a specific number of characters


with open('example.txt', 'r') as file:
content = file.read(10) # Read the first 10 characters
print(content)

In [ ]: # Example 1: Writing to a file


with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is the first example.')

In [ ]: # Example 2: Writing multiple lines


lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('example2.txt', 'w') as file:
file.writelines(lines)

In [ ]: # Example 1: Appending a single line


with open('example.txt', 'a') as file:
file.write('\nAppending example 1.')

In [ ]: # Example 2: Appending multiple lines


lines = ['\nAppended Line 1', '\nAppended Line 2']
with open('example2.txt', 'a') as file:
file.writelines(lines)

In [ ]: # Example 1: Reading a binary file


with open('image.jpg', 'rb') as file:
binary_content = file.read()
print(f'Total bytes: {len(binary_content)}')

In [ ]: # Example 2: Writing to a binary file


data = b'Binary Data Example'
with open('binary_file.bin', 'wb') as file:
file.write(data)

You might also like