EXPERIMENT No. 6
Python Lab Practical Record · Python programming laboratory
Read with diagrams, search and self-test
6A. Write random numbers to a file and read them back
Aim
To create a Python program that writes a list of random numbers to a file and reads them back.
Formula / Note
The numbers are random, so a different set is printed on every run.
Program (random_numbers_file.py)
# Exp 6A: Write random numbers to a file and read them back import random
file = open("numbers.txt", "w")
for i in range(5):
number = random.randint(1, 100)
file.write(str(number) + "\n")
file.close()file = open("numbers.txt", "r")
print(file.read())
file.close()Output
100 77 93 53 49
Result
Random numbers were written to a text file and read back successfully.
6B. Handle division by zero using try–except
Aim
To write a Python program to handle division by zero using try–except blocks.
Program (zero_division.py)
# Exp 6B: Handle division by zero using try-except
try:
a = 10 / 0
print("Result =", a)
except ZeroDivisionError:
print("Cannot divide by zero")Output
Cannot divide by zero
Result
The division-by-zero error was handled using a try–except block.
6C. Read data from a CSV file and count the rows
Aim
To write a Python program to read data from a CSV file and perform basic operations like counting the number of rows.
Input file student.csv
Roll No,Name,Branch 1,Rahul,Mechanical 2,Megha,Mechanical 3,Gagan,Mechanical
Program (csv_count_rows.py)
# Exp 6C: Read data from a CSV file and count the number of rows import csv
file = open("student.csv", "r")
data = csv.reader(file)
count = 0
for row in data:
count = count + 1
print("Number of rows =", count)
file.close()Output
Number of rows = 4
Result
Data was read from the CSV file and the number of rows was counted.