In: Computer Science
Write a function that takes three integers, n, a and b and a filename and writes to the file a list with n random integers between a and b. And then write a function that can read the files as generated above and return the values.
language: python
Dear Student ,
As per requirement submitted above kindly find below solution.
Python program :
import random #import random
#Python function to write numbers to the file
def writeNumbers(n,a,b,filename):
f=open(filename,"w") #open file for writing
randomNumberList=[] #list to store numbers
#using for loop
for i in range(0,n):
number=random.randint(a,b) #generate random number
randomNumberList.append(number) #store number in list
f.write(str(randomNumberList))#write list to the file
#function to read the file and return list
def readNumbers(filename):
f=open(filename,"r")#open file for read purpose
return f.read() #read file contents and return
#call function with value of a , b and n and file name
#function to write numbers to the file
writeNumbers(5,1,10,"numbers.txt")
#call function to read numbers and print numbers
print(readNumbers("numbers.txt"))
*****************************************
Please refer to the screenshot of the code to understand the indentation of the code :
==================================
Output :
Screen showing file numbers.txt :
Screen showing output :
NOTE :PLEASE FEEL FREE TO PROVIDE FEEDBACK ABOUT THE SOLUTION.