DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment - 3.3
Student Name: Ashwani Kumar UID:21BCS4688
Branch: BE- CSE Section/Group:713/A
Semester: 4th Date of Performance:11-05-23
Subject Name: Programming with Python Subject Code:21CSP-259
Aim of the practical: Program to demonstrate the basis of File Handling.
Objective: To learn the basis of File Handling.
1. Write a Python program to generate 26 text files named A.txt, B.txt, and so on up to
Z.txt
Code:-
import string
for letter in string.ascii_uppercase:
filename = f"{letter}.txt"
with open(filename, "w") as file:
file.write(f"This is the file {filename}.")
Output
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
2. Write a Python program to create a file where all letters of English alphabet are listed
by specified number of letters on each line
Code-
import string
num_letters_per_line = 5
alphabet = string.ascii_uppercase
with open("alphabet.txt", "w") as file:
for i in range(0, len(alphabet), num_letters_per_line):
line = alphabet[i:i+num_letters_per_line]
file.write(line + "\n")
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
3. Write a Python program to read a random line from a file
Code:
import random
filename = "alphabet.txt"
with open(filename, "r") as file:
lines = file.readlines()
random_line = random.choice(lines)
print(random_line.strip())
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
4. Write a Python program to count the frequency of words in a file
Code:
filename = "alphabet.txt"
word_counts = {}
with open(filename, "r") as file:
for line in file:
words = line.strip().split()
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
for word, count in word_counts.items():
print(f"{word}: {count}")
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
5. Write a Python program to copy the contents of a file to another file
Code:
source_file = "alphabet.txt"
destination_file = "destination.txt"
with open(source_file, "r") as source, open(destination_file, "w") as destination:
contents = source.read()
destination.write(contents)
print(f"Contents of {source_file} copied to {destination_file} successfully!")
Output: