Sunday, October 22, 2023

Python Programming - Lab- Core Lab 5 - Bsc CS DA -Bharathiar University - Program 9 - Write a python program that writes a series of random numbers to a file from 1 to n and display

 

B.Sc Computer Science with Data Analytics  

Python Programming - Lab

Core Lab 5  

Bharathiar University 

Program 9 - Write a python program that writes a series of random numbers to a file from 1 to n and display


SOURCE CODE:

# Function to generate and write random numbers to a file
import random


def write_random_numbers_to_file(f, n):
with open(filename, 'w') as f:
for _ in range(n):
random_number = random.randint(1, n)
f.write(str(random_number) + '\n')


# Function to read and display numbers from a file
def read_and_display_numbers(f):
with open(f, 'r') as file:
numbers = file.readlines()
print("Numbers from the file:")
for number in numbers:
print(number.strip())


# read file name and range for random numbers
filename = input("Enter file name: ")
n = int(input("Enter the range (n) for random numbers: "))

# Write random numbers to the file
write_random_numbers_to_file(filename, n)

# Read and display numbers from the file
read_and_display_numbers(filename)

OUTPUT:


Enter file name: C:\\Users\\Admin\\Desktop\\Sample.txt
Enter the range (n) for random numbers: 10
Random numbers to write in file
Random numbers read from file
Numbers from the file:
9
6
7
3
10
8
5
1
4
7
 Sample.txt file


No comments:

Post a Comment

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...