0% found this document useful (0 votes)
2 views10 pages

Python Functions File Handling Programs 10 Pages

The document contains a series of Python programs that demonstrate various functions related to file handling and data processing. Each section includes an aim, important points, program code, sample output, and explanations for functions such as calculating factorials, finding prime numbers, counting words, and managing student records. The programs illustrate practical applications of file operations, including reading, writing, appending, and searching data.

Uploaded by

Utkarsh C 7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Python Functions File Handling Programs 10 Pages

The document contains a series of Python programs that demonstrate various functions related to file handling and data processing. Each section includes an aim, important points, program code, sample output, and explanations for functions such as calculating factorials, finding prime numbers, counting words, and managing student records. The programs illustrate practical applications of file operations, including reading, writing, appending, and searching data.

Uploaded by

Utkarsh C 7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Page 1

1. Function to Calculate Factorial

Aim / Objective
This program shows how a function can return a value after doing repeated multiplication. It also includes
input validation.
Important Points
• Function used: factorial(n)
• Main concept: return statement and loop inside a function
• File handling link: the final answer is saved in result_factorial.txt
Program
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
answer = 1
for i in range(1, n + 1):
answer *= i
return answer

number = 5
result = factorial(number)

with open("result_factorial.txt", "w") as file:


[Link](f"Factorial of {number} is {result}")

print("Number:", number)
print("Factorial:", result)
print("Result saved in result_factorial.txt")

Sample Output
Number: 5
Factorial: 120
Result saved in result_factorial.txt

Explanation
The function receives a number, calculates the factorial and returns the answer. The with open() statement
creates a text file and safely closes it automatically. This page can be used directly in the practical file
because it contains aim, logic, program and output.

Computer Practical File - Python Functions and File Handling


Page 2
2. Function to Find Prime Numbers in a Range

Aim / Objective
This program uses one function to test prime numbers and another function to collect all prime numbers
between two limits.
Important Points
• Function used: is_prime(n)
• Function used: primes_between(start, end)
• File handling link: all prime numbers are written to [Link]
Program
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

def primes_between(start, end):


prime_list = []
for number in range(start, end + 1):
if is_prime(number):
prime_list.append(number)
return prime_list

start, end = 10, 40


answer = primes_between(start, end)

with open("[Link]", "w") as file:


[Link]("Prime numbers: " + str(answer))

print("Prime numbers from", start, "to", end)


print(answer)

Sample Output
Prime numbers from 10 to 40
[11, 13, 17, 19, 23, 29, 31, 37]

Explanation
The program checks divisibility only up to the square root of the number, which makes it faster. The
returned list is saved in a file. This page can be used directly in the practical file because it contains aim,
logic, program and output.

Computer Practical File - Python Functions and File Handling


Page 3
3. Function to Count Words in a Text File

Aim / Objective
This program creates a file, reads it again, and counts the number of words using a function.
Important Points
• Function used: count_words(filename)
• Main concept: read() and split()
• File handling link: reading data from a text file
Program
def count words(filename):
with open(filename, "r") as file:
data = [Link]()
words = [Link]()
return len(words)

with open("[Link]", "w") as file:


[Link]("Python is simple. Functions make programs reusable.")

word_count = count_words("[Link]")

print("File name: [Link]")


print("Total words:", word_count)

Sample Output
File name: [Link]
Total words: 7

Explanation
The write mode creates the sample file first. Then read mode gets the full text. split() separates words by
spaces and new lines. This page can be used directly in the practical file because it contains aim, logic,
program and output.

Computer Practical File - Python Functions and File Handling


Page 4
4. Function to Copy One File into Another

Aim / Objective
This program uses a function to copy the complete content of one text file into another text file.
Important Points
• Function used: copy_file(source, destination)
• Main concept: reading from one file and writing to another
• File handling link: file copy operation
Program
def copy_file(source, destination):
with open(source, "r") as file1:
content = [Link]()

with open(destination, "w") as file2:


[Link](content)

return len(content)

with open("[Link]", "w") as file:


[Link]("This is the original file.
It has two lines.")

characters = copy_file("[Link]", "[Link]")

print("File copied successfully")


print("Characters copied:", characters)

Sample Output
File copied successfully
Characters copied: 43

Explanation
The source file is opened in read mode and the destination file is opened in write mode. The function
returns the total characters copied. This page can be used directly in the practical file because it contains
aim, logic, program and output.

Computer Practical File - Python Functions and File Handling


Page 5
5. Function to Append Student Records

Aim / Objective
This program appends student records to a file and then displays all records neatly.
Important Points
• Function used: add_student(name, marks)
• Main concept: append mode
• File handling link: saving multiple records line by line
Program
def add_student(name, marks):
with open("[Link]", "a") as file:
[Link](f"{name},{marks}
")

def show_students():
with open("[Link]", "r") as file:
for line in file:
name, marks = [Link]().split(",")
print(name, "scored", marks, "marks")

open("[Link]", "w").close()
add_student("Aman", 88)
add_student("Riya", 94)
add_student("Kabir", 79)

print("Student Records")
show_students()

Sample Output
Student Records
Aman scored 88 marks
Riya scored 94 marks
Kabir scored 79 marks

Explanation
Append mode adds new data at the end of the file without removing old records. Each record is stored in
comma separated form. This page can be used directly in the practical file because it contains aim, logic,
program and output.

Computer Practical File - Python Functions and File Handling


Page 6
6. Function to Search a Word in a File

Aim / Objective
This program searches how many times a given word appears in a text file. It ignores letter case while
searching.
Important Points
• Function used: search_word(filename, word)
• Main concept: lower(), count() and file reading
• File handling link: searching inside file content
Program
def search_word(filename, word):
with open(filename, "r") as file:
data = [Link]().lower()
return [Link]([Link]())

with open("[Link]", "w") as file:


[Link]("Python functions are useful. Python files store data.")

word = "python"
frequency = search_word("[Link]", word)

print("Word searched:", word)


print("Frequency:", frequency)

Sample Output
Word searched: python
Frequency: 2

Explanation
The data and the searched word are converted to lower case. This makes Python and python count as the
same word. This page can be used directly in the practical file because it contains aim, logic, program and
output.

Computer Practical File - Python Functions and File Handling


Page 7
7. Function to Calculate Average Marks from File

Aim / Objective
This program reads marks from a file and calculates their average using a function.
Important Points
• Function used: calculate_average(filename)
• Main concept: list, sum() and len()
• File handling link: numerical data reading from file
Program
def calculate_average(filename):
marks = []
with open(filename, "r") as file:
for line in file:
[Link](int([Link]()))
return sum(marks) / len(marks)

with open("[Link]", "w") as file:


[Link]("82
91
76
89
95")

average = calculate_average("[Link]")

print("Marks are stored in [Link]")


print("Average marks:", average)

Sample Output
Marks are stored in [Link]
Average marks: 86.6

Explanation
Each line has one mark. strip() removes the new line character and int() converts the value into a number for
calculation. This page can be used directly in the practical file because it contains aim, logic, program and
output.

Computer Practical File - Python Functions and File Handling


Page 8
8. Function to Store and Read Dictionary Data

Aim / Objective
This program stores item prices in a file and reads them back into a dictionary.
Important Points
• Function used: save_items(items)
• Function used: read_items()
• File handling link: storing key-value data
Program
def save_items(items):
with open("[Link]", "w") as file:
for item, price in [Link]():
[Link](f"{item}:{price}
")

def read_items():
items = {}
with open("[Link]", "r") as file:
for line in file:
item, price = [Link]().split(":")
items[item] = int(price)
return items

shop = {"Pen": 10, "Notebook": 45, "Pencil": 5}


save_items(shop)
loaded_items = read_items()

print("Items loaded from file:")


print(loaded_items)

Sample Output
Items loaded from file:
{'Pen': 10, 'Notebook': 45, 'Pencil': 5}

Explanation
The dictionary is saved line by line using a colon between item and price. While reading, split() separates the
key and value. This page can be used directly in the practical file because it contains aim, logic, program and
output.

Computer Practical File - Python Functions and File Handling


Page 9
9. Function to Count Lines, Words and Characters

Aim / Objective
This program gives a small file report by counting lines, words and characters.
Important Points
• Function used: file_report(filename)
• Main concept: tuple return value
• File handling link: complete text analysis of a file
Program
def file_report(filename):
with open(filename, "r") as file:
lines = [Link]()

line_count = len(lines)
word_count = 0
char_count = 0

for line in lines:


word_count += len([Link]())
char_count += len(line)

return line_count, word_count, char_count

with open("[Link]", "w") as file:


[Link]("Python is powerful.
File handling is useful.")

lines, words, characters = file_report("[Link]")

print("Lines:", lines)
print("Words:", words)
print("Characters:", characters)

Sample Output
Lines: 2
Words: 6
Characters: 43

Explanation
A function can return more than one value as a tuple. readlines() reads every line and keeps them in a list.
This page can be used directly in the practical file because it contains aim, logic, program and output.

Computer Practical File - Python Functions and File Handling


Page 10
10. Menu Driven File Handling Program

Aim / Objective
This program uses functions to add tasks, view tasks and clear tasks from a simple to-do list file.
Important Points
• Functions used: add_task(), view_tasks(), clear_tasks()
• Main concept: menu driven program structure
• File handling link: append, read and write modes together
Program
def add_task(task):
with open("[Link]", "a") as file:
[Link](task + "
")

def view_tasks():
with open("[Link]", "r") as file:
tasks = [Link]()
for number, task in enumerate(tasks, start=1):
print(number, [Link]())

def clear_tasks():
open("[Link]", "w").close()

clear_tasks()
add_task("Revise Python functions")
add_task("Practice file handling")
add_task("Prepare practical file")

print("My To-Do List")


view_tasks()

Sample Output
My To-Do List
1 Revise Python functions
2 Practice file handling
3 Prepare practical file

Explanation
This is a good practical example because it combines several small functions. Each function has a single clear
responsibility. This page can be used directly in the practical file because it contains aim, logic, program and
output.

Computer Practical File - Python Functions and File Handling

You might also like