0% found this document useful (0 votes)
4 views12 pages

Python LectureNotes UNIT 5

Unit 5 covers file handling in Python, detailing operations like creating, opening, reading, writing, and closing files. It explains the importance of file handling for data permanence, memory efficiency, and task automation, along with various file modes such as read, write, append, and binary. The document also includes examples of reading and writing CSV files, exception handling, and practical programming exercises related to file operations.

Uploaded by

gunnamanga
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)
4 views12 pages

Python LectureNotes UNIT 5

Unit 5 covers file handling in Python, detailing operations like creating, opening, reading, writing, and closing files. It explains the importance of file handling for data permanence, memory efficiency, and task automation, along with various file modes such as read, write, append, and binary. The document also includes examples of reading and writing CSV files, exception handling, and practical programming exercises related to file operations.

Uploaded by

gunnamanga
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

UNIT-5: File Handling in Python

File handling refers to the process of performing operations on a file, such as creating, opening,
reading, writing and closing it through a programming interface. It involves managing the data flow
between the program and the file system on the storage device, ensuring that data is handled safely
and efficiently.
Why do we need File Handling
• To store data permanently, even after the program ends.
• To access external files like .txt, .csv, .json, etc.
• To process large files efficiently without using much memory.
• To automate tasks like reading configs or saving outputs.

Opening a File
To open a file, we can use open() function, which requires file-path and mode as arguments.
Syntax: file = open('[Link]', 'mode')
• [Link]: name (or path) of the file to be opened.
• mode: mode in which you want to open the file (read, write, append, etc.).
Note: If you don’t specify the mode, Python uses 'r' (read mode) by default.
Example:

Explanation: This code opens file [Link] in read mode. If the file exists, it returns a file object
connected to that file; if the file does not exist, Python raises a FileNotFoundError.
Closing a File
The [Link]() method closes the file and releases the system resources. If the file was opened in write
or append mode, closing ensures that all changes are properly saved.

We will also see later how closing can be handled automatically using the with statement and how
to ensure files close properly using exception handling.

Dept. of ECE, GGU 1 Dr. P. Venkatrao, Professor, ECE


Checking File Properties
Once the file is open, we can check some of its properties:

Explanation:
• [Link]: Returns the name of the file that was opened (in this case, "[Link]").
• [Link]: Tells us the mode in which the file was opened. Here, it’s 'r' which means read
mode.
• [Link]: Returns a boolean value- False when file is currently open otherwise True.
Reading a File
Reading a file can be achieved by [Link]() which reads the entire content of the file. After reading,
it’s good practice to close the file to free up system resources.
Example: Reading a File in Read Mode (r)

Writing a File
In Python, writing to a file is done using the mode "w". This creates a new file if it doesn’t exist, or
overwrites the existing file if it does. The write() method is used to add content. After writing, make
sure to close the file.
Example: Writing to a file (overwrites if file exists)

Dept. of ECE, GGU 2 Dr. P. Venkatrao, Professor, ECE


Explanation:
• "w" mode opens the file for writing (overwrites existing content if the file already exists).
• write() method adds new text to the file.
• When using with, the file closes automatically at the end of the block.
Using with Statement
Instead of manually opening and closing the file, you can use the with statement, which
automatically handles closing. This reduces the risk of file corruption and resource leakage.
Example: Let's assume we have a file named [Link] that contains text "Hello, World!".

Handling Exceptions When Closing a File


It's important to handle exceptions to ensure that files are closed properly, even if an error occurs
during file operations. Here, the finally block ensures the file is closed even if an error occurs.

Explanation:
• try: Starts the block to handle code that might raise an error.
• open(): Opens the file in read mode.
• read(): Reads the content of the file.
• finally: Ensures the code inside it runs no matter what.

Dept. of ECE, GGU 3 Dr. P. Venkatrao, Professor, ECE


Different File Mode in Python
Examples of Common Modes
Let's say we have a file named [Link] with the content: Hello Geeks
1. Read Mode ('r')
This mode allows you to open a file for reading only. If the file does not exist, it will raise
a FileNotFoundError.
Example: In this example, a file named '[Link]' is opened in read mode ('r'), and its content is
read and stored in the variable 'content' using a 'with' statement, ensuring proper resource
management by automatically closing the file after use.

2. Write Mode ('w')


Opens the file for writing only. If the file exists, its content is deleted. If not, a new file is created.
Example: In this example, a file named '[Link]' is opened in write mode ('w'), and the string
'Hello, world!' is written into the file.

Note: If you were to open the file "[Link]" after running this code, you would find that it contains
the text "Hello, world!" as the previous content "Hello Geeks" will be deleted.
3. Append Mode ('a')
Opens the file to add content at the end without deleting existing data. If the file doesn’t exist, it
creates a new one.
Example: In this example, a file named '[Link]' is opened in append mode ('a'), and the string
'\n This is a new line.' is written to the end of the file.

Dept. of ECE, GGU 4 Dr. P. Venkatrao, Professor, ECE


The code will then write the string "\nThis is a new line." to the file, appending it to the existing
content or creating a new line if the file is empty.
4. Binary Mode ('b')
Used for non-text files like images or audio. Always combined with 'r', 'w', or 'a
Example: In this example, a file named '[Link]' is opened in binary read mode ('rb'). The binary
data is read from the file using the 'read()' method and stored in the variable 'data'.

5. Read and Write Mode ('r+')


Opens the file for both reading and writing. Starts at the beginning of the file.
Raises FileNotFoundError if the file doesn’t exist.

6. Write and Read Mode ('w+')


This mode allows you to open a file for both reading and writing. If the file already exists, it will
truncate the file to zero length. If the file does not exist, it will create a new file.
Example: In this example, a file named '[Link]' is opened in write and read mode ('w+').

Dept. of ECE, GGU 5 Dr. P. Venkatrao, Professor, ECE


Explanation: the output of this code is "Hello, world!". Since the file was truncated and the pointer
was moved to the beginning before reading, the contents of the file will be exactly what was written
to it. So, content will contain the string "Hello, world!".
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many characters
you want to return:

Read Lines
You can return one line by using the readline() method:

By calling readline() two times, you can read the two first lines:

By looping through the lines of the file, you can read the whole file, line by line:

Dept. of ECE, GGU 6 Dr. P. Venkatrao, Professor, ECE


Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is one of the most widely used formats for storing and
exchanging structured data between different applications, including databases and spreadsheets.
CSV files store tabular data, where each data field is separated by a delimiter, typically a comma.
Python provides built-in support for handling CSV files through the csv module, making it easy to
read, write and manipulate CSV data efficiently.
However, we first need to import the module using: import csv
Reading a CSV File in Python
To read a CSV file, Python provides the [Link] class, which reads data in a structured format.
The first step involves opening the CSV file using the open() function in read mode ('r').
The [Link]() function then reads the file, returning an iterable reader object.
Example:

Explanation: The csv module reads [Link] using [Link](file), iterating row by row.
The with statement ensures proper file closure. Each row is returned as a list of column values.
Use next(csvFile) to skip the header

Dept. of ECE, GGU 7 Dr. P. Venkatrao, Professor, ECE


Writing to a csv file in python
Python provides the [Link] class to write data to a CSV file. It converts user data into delimited
strings before writing them to a file. While opening the file, using newline = ' ' prevents unnecessary
newlines when writing.
Writing a single row: writerow(fields)
Writing multiple rows: writerows(rows)
Example:

Output: A file named university_records.csv will be created containing the following data.

Dept. of ECE, GGU 8 Dr. P. Venkatrao, Professor, ECE


1. Write a program to sort words in a file and put them in another file. The output file should have
only lower-case words, so any upper-case words from the source must be lowered.

try:
# Open the input file in read mode
with open("[Link]", "r") as infile:
content = [Link]()
# Split content into words
words = [Link]()
# Convert all words to lowercase
words = [[Link]() for word in words]
# Sort the words
[Link]()
# Open the output file in write mode
with open("[Link]", "w") as outfile:
# Write sorted words into the file
for word in words:
[Link](word + "\n")
print("Words sorted and written to [Link] successfully!")

except FileNotFoundError:
print("Error: [Link] file not found.")

except Exception as e:
print("An error occurred:", e)

Sample Output:
[Link]
Apple banana Orange apple Mango BANANA
[Link]
apple
apple
banana
banana
mango
orange

Dept. of ECE, GGU 9 Dr. P. Venkatrao, Professor, ECE


2. File Exception Handling: Implement a function that reads data from a file and handles file-
related exceptions such as FileNotFoundError and PermissionError.

def read_file(filename):
try:
with open(filename, "r") as file:
data = [Link]()
print("File Content:\n")
print(data)

except FileNotFoundError:
print("Error: The file does not exist.")

except PermissionError:
print("Error: Permission denied. Cannot access the file.")

except Exception as e:
print("An unexpected error occurred:", e)

finally:
print("\nFile operation attempted.")

# Example usage
read_file("[Link]")

Sample Output:
Case 1: File not found
Error: The file does not exist.
File operation attempted.
Case 2: Permission denied
Error: Permission denied. Cannot access the file.
File operation attempted.
Case 3: Successful read
File Content:
Hello World!
File operation attempted.

Dept. of ECE, GGU 10 Dr. P. Venkatrao, Professor, ECE


3. Python program to print each line of a file in reverse order.

def reverse_lines(filename):
try:
with open(filename, "r") as file:
for line in file:
# Remove newline, reverse the line, then print
print([Link]()[::-1])

except FileNotFoundError:
print("Error: File not found.")

except PermissionError:
print("Error: Permission denied.")

except Exception as e:
print("An unexpected error occurred:", e)

# Example usage
reverse_lines("[Link]")

Sample Output:
[Link]
Hello World
Python Programming
ECE Department

Output
dlroW olleH
gnimmargorP nohtyP
tnemtrapeD ECE

Dept. of ECE, GGU 11 Dr. P. Venkatrao, Professor, ECE


4. Python program to compute the number of characters, words and lines in a file.

def file_statistics(filename):
try:
with open(filename, "r") as file:
content = [Link]()
# Count characters
char_count = len(content)
# Count words
words = [Link]()
word_count = len(words)
# Count lines
lines = [Link]()
line_count = len(lines)

print("Number of characters:", char_count)


print("Number of words:", word_count)
print("Number of lines:", line_count)

except FileNotFoundError:
print("Error: File not found.")

except PermissionError:
print("Error: Permission denied.")

except Exception as e:
print("An unexpected error occurred:", e)

# Example usage
file_statistics("[Link]")

Dept. of ECE, GGU 12 Dr. P. Venkatrao, Professor, ECE

You might also like