In: Computer Science
Write a program that creates an output file named rand_nums.txt. Open the file and write 100 random integers between -50 and +50 (inclusive) to the file. Be sure to handle any file IO exceptions. Remember to close the file.
Write a program that opens rand_nums.txt for input. Create two output files pos.txt and neg.txt. Read through the input file, one line at a time, converting each line into an integer (no exception handling, yet). If the number is positive, write it to pos.txt (one number per line). If the number is negative, write it to neg.txt. If the number is 0, do nothing. Be sure to close all files.
You have created rand_nums.txt, and you know all the numbers are valid. What if instead you used the data file bad_rand_nums.txt provided? This file contains invalid data. Modify your program from the previous part to use exception handling to disregard any invalid data and continue with the next line of data.
Program 1:
import random
rndfile = open("rand_nums.txt","w")
for i in range(100):
line = str(random.randint(-50,50))
line = line + "\n"
rndfile.write(line)
rndfile.close()
Program 2 (for valid numbers in rand_nums.txt):
rndfile = open("rand_nums.txt",'r')
lines = rndfile.readlines()
pos = open("pos.txt","w")
neg = open("neg.txt","w")
for line in lines:
lx = int(line)
if(lx>0):
pos.write(line)
elif(lx<0):
neg.write(line)
pos.close()
neg.close()
rndfile.close()
Program 3 (for invalid numbers in bad_rand_nums.txt):
#function defined to check if
#the line is a valid integer of not
def isNumber(s):
if(s[0] == '-'):
p = s[1:]
else:
p = s[0:]
for i in range(len(p)-2):
if p[i].isdigit() != True:
return False
return True
rndfile = open("bad_rand_nums.txt",'r')
lines = rndfile.readlines()
pos = open("pos.txt","w")
neg = open("neg.txt","w")
for line in lines:
if(isNumber(line)):
lx = int(line)
if(lx>0):
pos.write(line)
elif(lx<0):
neg.write(line)
pos.close()
neg.close()
rndfile.close()