PYTHON PROGRAMS
FILE HANDLING PROGRAMS
PROGRAM 1: WRITE TO A FILE
THIS PROGRAM CREATES A FILE NAMED [Link] AND WRITES A LIST OF NAMES TO
IT
PYTHON CODE:
# Program 1: Write to a File
def write_names_to_file():
names = ["Alice", "Bob", "Charlie", "David"]
with open("[Link]", "w") as file:
for name in names:
[Link](name + "\n")
print("[Link] created successfully.")
write_names_to_file()
OUTPUT:
[Link] created successfully.
Program 2: Read from a File
This program reads the names from the [Link] file and prints them.
PYTHON CODE:
# Program 2: Read from a File
def read_names_from_file():
print("Names from file:")
with open("[Link]", "r") as file:
for line in file:
print([Link]())
read_names_from_file()
OUTPUT:
Names from file:
Alice
Bob
Charlie
David
Program 3: Append to a File
This program adds two new names to the end of the [Link] file.
PYTHON CODE :
# Program 3: Append to a File
def append_names_to_file():
new_names = ["Eva", "Frank"]
with open("[Link]", "a") as file:
for name in new_names:
[Link](name + "\n")
print("New names appended to [Link].")
append_names_to_file()
OUTPUT :
New names appended to [Link].
Program 4: Count Lines, Words, and Characters
This program counts the lines, words, and characters in [Link].
PYTHON CODE :
# Program 4: Count Lines, Words, and Characters
def count_file_stats():
line_count = 0
word_count = 0
char_count = 0
try:
with open("[Link]", "r") as file:
for line in file:
line_count += 1
words = [Link]()
word_count += len(words)
char_count += len(line)
print(f"Total Lines: {line_count}")
print(f"Total Words: {word_count}")
print(f"Total Characters: {char_count}")
except FileNotFoundError:
print("File not found.")
count_file_stats()
OUTPUT:
Total Lines: 6
Total Words: 6
Total Characters: 35
Program 5: Search for a Specific Word
This program searches for "Charlie" in [Link].
PYTHON CODE:
# Program 5: Search for a Specific Word
def search_word_in_file(word):
found = False
with open("[Link]", "r") as file:
for line in file:
if word in line:
found = True
break
if found:
print(f"'{word}' found in the file.")
else:
print(f"'{word}' not found in the file.")
search_word_in_file("Charlie")
OUTPUT:
'Charlie' found in the file.
Program 6: Copy File Contents
This program copies the content from [Link] to names_copy.txt.
PYTHON CODE:
# Program 6: Copy File Contents
def copy_file(source, destination):
with open(source, "r") as source_file:
content = source_file.read()
with open(destination, "w") as dest_file:
dest_file.write(content)
print(f"Content from '{source}' copied to '{destination}'.")
copy_file("[Link]", "names_copy.txt")
OUTPUT:
Content from '[Link]' copied to 'names_copy.txt'.
Program 7: Count Word Frequency
This program counts the frequency of each word in the file. We'll use a
sample text file sample_text.txt.
PYTHON CODE:
# First, create a sample file for this program
with open("sample_text.txt", "w") as file:
[Link]("Python is a great language. Python is versatile.")
# Program 7: Count Word Frequency
def count_word_frequency(filename):
word_freq = {}
with open(filename, "r") as file:
content = [Link]().lower().replace('.', '').strip().split()
for word in content:
word_freq[word] = word_freq.get(word, 0) + 1
print("Word frequencies:")
for word, count in word_freq.items():
print(f"{word}: {count}")
count_word_frequency("sample_text.txt")
OUTPUT:
Word frequencies:
python: 2
is: 2
a: 1
great: 1
language: 1
versatile: 1
Function Programs
Program 8: Simple Sum Function
This program defines a function to calculate the sum of two numbers.
PYTHON CODE:
# Program 8: Simple Sum Function
def calculate_sum(a, b):
return a + b
num1 = 15
num2 = 25
total = calculate_sum(num1, num2)
print(f"The sum of {num1} and {num2} is {total}.")
OUTPUT:
The sum of 15 and 25 is 40.
Program 9: Factorial with Recursion
This program uses a recursive function to find the factorial of a number.
PYTHON CODE:
# Program 9: Factorial with Recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
number = 5
print(f"The factorial of {number} is {factorial(number)}.")
OUTPUT:
The factorial of 5 is 120.
Program 10: Function Modifying a List
This program uses a function that sorts a list passed as an argument.
PYTHON CODE:
# Program 10: Function Modifying a List
def sort_list(my_list):
my_list.sort()
numbers = [8, 3, 1, 6, 2]
print(f"Original list: {numbers}")
sort_list(numbers)
print(f"Sorted list: {numbers}")
OUTPUT:
Original list: [8, 3, 1, 6, 2]
Sorted list: [1, 2, 3, 6, 8]
Program 11: Function with Default Arguments
This program demonstrates a function with a default value for the message
argument.
PYTHON CODE:
# Program 11: Function with Default Arguments
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice")
greet("Bob", "Hi there")
OUTPUT:
Hello, Alice!
Hi there, Bob!
Program 12: Function with Variable Arguments (*args)
This program uses *args to find the maximum value from a variable number
of integers.
PYTHON CODE:
# Program 12: Function with Variable Arguments (*args)
def find_max(*numbers):
if not numbers:
return None
return max(numbers)
print(f"Max of 1, 5, 2, 9 is: {find_max(1, 5, 2, 9)}")
print(f"Max of 100, 200 is: {find_max(100, 200)}")
OUTPUT:
Max of 1, 5, 2, 9 is: 9
Max of 100, 200 is: 200
Program 13: Local and Global Scope
This program illustrates the difference between local and global variables.
PYTHON CODE:
# Program 13: Local and Global Scope
global_var = "I am global"
def scope_demo():
local_var = "I am local"
print(f"Inside function: {local_var}")
print(f"Inside function: {global_var}")
scope_demo()
print(f"Outside function: {global_var}")
# print(local_var) # This would cause an error
OUTPUT:
Inside function: I am local
Inside function: I am global
Outside function: I am global
Program 14: Function to Write a List to a File
This program combines functions and file handling to write a list to a file.
PYTHON CODE:
# Program 14: Function to Write a List to a File
def write_list_to_file(filename, data_list):
with open(filename, "w") as file:
for item in data_list:
[Link](str(item) + "\n")
print(f"List successfully written to {filename}.")
numbers_list = [10, 20, 30, 40]
write_list_to_file("[Link]", numbers_list)