ARUSHA TECHNICAL COLLEGE
• MODULE: PYTHON PROGRAMMING
• MODULE CODE: CST 06102
• GROUP ASSIGNMENT: FILE HANDLING
GROUP MEMBERS
Names Admission number
David Nagol 23051012370
Ebenezer Shedrack 22051012034
Edward Ernest 23051012363
Edgar Richard 23051012353
Edwin Florence 22051012036
Elenesia Mhema 23051012354
Emmanuel Noel 22051012044
Eva chache 22050512007
Faith Cletus 22051012048
Godliving Leonard 22051012283
Hamis Issa 22051012061
Innocent Byabato 21051102263
Introduction to File Handling
Understanding Files in Python
• Files are a key way to persist data beyond the life of a
program.
• They allow programs to store, retrieve, and manipulate
data persistently.
• Python provides built-in functions to handle files
efficiently.
Persistence in Programming
The Need for Persistence
• Persistence refers to the ability to store data
permanently.
• Data stored in a program's memory (RAM) is lost once
the program stops.
• - Files serve as a method to maintain data over time,
enabling programs to read from and write to these files
whenever needed.
Opening Files
How to Open Files in Python
• Python’s `open()` function is used to open files.
• Syntax: `file_handle = open('filename', 'mode')`.
• `'r'` for reading, `'w'` for writing, `'a'` for appending.
• The `open()` function returns a file handle, which acts
as a reference to the file for further operations.
What
Next?
Software
Input and Central
Output Processing Network
Devices Unit
Main
Secondary
Memory
Memory
Secondary memory
Reading Files
Reading Content from Files
• The `read()` method reads the entire content of a file as a
single string.
• `readline()` reads one line at a time, and `readlines()` reads
all lines into a list.
• Example: Reading a file line by line to count the number of
lines.
```python
fhand = open('[Link]')
count = 0
for line in fhand:
count += 1
print('Line Count:', count)
Writing to Files
Writing Data to Files
• Files opened in `'w'` mode are truncated (emptied)
before writing.
• - The `write()` method is used to write strings to a file.
• Example:
```python
fout = open('[Link]', 'w')
[Link]('Hello, world!\n')
[Link]()
• - It’s important to close files after operations to ensure
data is saved and resources are released.
Letting Users Choose Files
Dynamic File Selection
• Programs can prompt users to input the filename they
want to work with.
• Example:
python
fname = input('Enter the file name: ')
fhand = open(fname)
Handling Errors with try-except
Managing File Errors
• Opening a non-existent file results in a
`FileNotFoundError`.
• Use `try` and `except` to handle such errors gracefully.
```python
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
quit()
File handle
open H
close From stephen.m..
N
Return-Path: <p..
D
read Date: Sat, 5 Jan ..
L
To: source@coll..
write E From: stephen...
Subject: [sakai]...
Details: http:/...
Your
…
Program
Writing to Files
Writing Data to Files
• Files can be written to using `write()` method, and
different modes (`'w'` for writing and `'a'` for
appending).
• Always ensure you close the file using `close()` method
to avoid data loss.
Example Programs
• Example: Counting Words
An example program that reads a file, counts the occurrences
of each word, and prints the word with the highest frequency
```python
def read_file(file_path):
"""Reads the content of a file and returns it as a string."""
with open(file_path, 'r') as file:
content = [Link]()
return content
Continue…
def count_words(text):
"""Counts the occurrences of each word in the given
text."""
word_counts = {}
words = [Link]()
for word in words:
word = [Link]().strip(",.!?;:\"'()[]{}") #
Normalize the words by converting to lowercase and
stripping punctuation
if word in word_counts:
word_counts[word] += 1
Continue…
else:
word_counts[word] = 1
return word_counts
def find_most_frequent_word(word_counts):
"""Finds the word with the highest frequency in the
word count dictionary."""
most_frequent_word = max(word_counts,
key=word_counts.get) return most_frequent_word,
word_counts[most_frequent_word]
Continue…
# Example usage
if __name__ == "__main__":
file_path = "[Link]" # Replace with your file
path
text = read_file(file_path)
word_counts = count_words(text)
most_frequent_word, frequency =
find_most_frequent_word(word_counts)
print(f"The most frequent word is
'{most_frequent_word}' with a frequency of
{frequency}.")
```
Continue…
Explanation:
• `read_file(file_path)`: Reads the entire content of a file
and returns it as a string.
• `count_words(text)`: Splits the text into words,
normalizes them by converting to lowercase and
removing punctuation, then counts the occurrences of
each word using a dictionary.
• `find_most_frequent_word(word_counts)`: Finds and
returns the word with the highest frequency and its
count from the word count dictionary.
• `main`: Reads the file, counts the words, finds the most
frequent word, and prints it along with its frequency.
Summary and Best Practices
• File handling is crucial for data persistence.
• Always close files after operations.
• Handle errors to make your program more robust.
• Practice reading and writing files to understand the
nuances better
Godliving Mollel.
• Example:
Program that check if a file named [Link] exist in the current
directory
File name = ‘[Link]’
If [Link](filename):
print(“file found”)
Else:
print(“file not found”)
Eva Chahe
• Example:
Write a program to read the content of [Link].
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Edgar Richard
• Example:
Write a program that writes "Hello, World!" to [Link]
with open("[Link]", "w") as file:
[Link]("Hello, World!")
Faith cletus
• Example:
Write a program to append "Welcome to Python!" to
[Link]
with open("[Link]", "a") as file:
[Link]("\nWelcome to Python!")
Elenesia Mhema
• Example:
Write a program that reads [Link] line by line.
with open("[Link]", "r") as file:
for line in file:
print([Link]()) # Removing trailing newline
characters
Edward Ernest
• Example:
Write a program that stores lines of [Link] in a list and
prints them.
with open("[Link]", "r") as file:
lines = [Link]()
print(lines)
David Nagol
• Example:
Write a program that writes a list of names to a file, with
each name on a new line.
names = ["Alice", "Bob", "Charlie"]
with open("[Link]", "w") as file:
Emmanuel Noel
• Example:
Modify the program below to handle the case when
[Link] does not exist.
with open("[Link]", "r") as file:
content = [Link]()
print(content)
except FileNotFoundError:
print("File not found. Please check the file name.")
Hamis Issa.
• Example:
Write a program that reads [Link] only if it exists.
import os
if [Link]("[Link]"):
with open("[Link]", "r") as file:
print([Link]())
else:
print("File does not exist.")
Innocent byabato
• Example:
Write a program that writes a list of student names and grades to
[Link]
import csv
students = [["Name", "Grade"], ["Alice", "A"], ["Bob", "B"],
["Charlie", "A"]]
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](students)
Edwin Florence
• Example:
Write a program that reads and prints the content of
[Link]
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
Ebenezer Shedrack
• Example:
Write a program that counts the number of words in
[Link].
with open("[Link]", "r") as file:
content = [Link]()
words = [Link]()
print("Word count:", len(words))
Questions:
1. Write a Python program to check if a file is empty.
2. Create a program to write data from a list of tuples to a
CSV file.
3. Write a Python program to read a binary file and print
its contents as hexadecimal.
4. Create a Python program to find the size of a file in
bytes.
5. Write a program to find and replace a word in a text file.
6. Create a Python program to rename a file.
7. Write a program that reads a file and prints all lines that contain
a specific word.
8. Create a Python program to read and print the content of a CSV
file.
9. Write a program to merge multiple text files into a single text
file.
10. Create a Python program to count the frequency of each word
in a text file.
11. Write a Python program to copy the contents of one file to
another file.
12. Write a python program that read the content of a file named
[Link] and print each line to the console.