Question

In: Computer Science

Write a program that creates an output file named rand_nums.txt. Open the file and write 100...

  1. 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.

Solutions

Expert Solution

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()


Related Solutions

Write a complete Java program that does the following: Open an input file named data.txt that...
Write a complete Java program that does the following: Open an input file named data.txt that consists of a series of unknown number of integers. If data.txt does not exist, give an appropriate error message and terminate the program. Define a constant MAX of value 100 and create an array of size MAX to hold items from the input file. Make sure your program will not generate ArrayIndexOutOfBounds exception. Open an output file named result.txt and write the array elements...
Write a C++ program that creates a file called Readings.txt. Inside the file, your program must...
Write a C++ program that creates a file called Readings.txt. Inside the file, your program must create a list. The list is composed of integer double pairs. There is one pair per line. The integers are in sequence (0, 1, 2, 3, ...) beginning with zero and ending with some random value between 512 and 1024. The doubles should be random values between 50.000 and 90.000. The doubles only have 3 decimal places. The file should look like this (of...
Write a script named numberlines.py. This script creates a program listing from a source program. This...
Write a script named numberlines.py. This script creates a program listing from a source program. This script should: Prompt the user for the names of two files. The input filename could be the name of the script itself, but be careful to use a different output filename! The script copies the lines of text from the input file to the output file, numbering each line as it goes. The line numbers should be right-justified in 4 columns, so that the...
Write a program in a script file that creates m × n matrix with elements that...
Write a program in a script file that creates m × n matrix with elements that have the following values. The value of each element in the last row is the number of the column. The value of each element in the last column is the number of row +1. For the rest of the elements, each has a value equal to the sum of the element below it and the element to the right.
Write a c program that creates a struct to be able to read a .img file...
Write a c program that creates a struct to be able to read a .img file and a .pat file.
Write a program that creates a concordance. There will be two ways to create a concordance. The first requires a document to be read from an input file, and the concordance data is written to an output file.
Concepts tested by this program            Hash Table,            Link List,hash code, buckets/chaining,exception handling, read/write files (FileChooser)A concordance lists every word that occurs in a document in alphabetical order, and for each word it gives the line number of every line in the document where the word occurs.Write a program that creates a concordance. There will be two ways to create a concordance. The first requires a document to be read from an input file, and the concordance data is written to...
Write a program in Java, that creates a Jframe with a menu containing only file. Inside...
Write a program in Java, that creates a Jframe with a menu containing only file. Inside file there should be items: Open, Save, and Save As. Selecting open prompts the user to input a file name to a txt document containing employee information and displays a Jtable with the information, which can be edited. With column headers {"First Name" , "Last Name" , "Occupation" , "Office #"} Example: Gary Osbourn Teacher 113 Michelle Ramirez Teacher 101 Ava Gomez Principal 120...
Write a program that creates a file called "data.dat" in the current directory. Prompt the user...
Write a program that creates a file called "data.dat" in the current directory. Prompt the user for five numbers, and write them, one at a time, on both the screen and into the file. Close the file, then open it again for reading only, and display the contents on the screen. Handle error conditions that may occur. Please Need this to be done in PERL. Thanks
In this assignment you will write a PHP program that reads from a data file, creates...
In this assignment you will write a PHP program that reads from a data file, creates an associative array, sorts the data by key and displays the information in an HTML table. Create a PHP file called hw4.php that will do the following: - Display your name. - Read text data from a file. The data file is hw3.txt. The file hw3.txt will hold the following text: PQRParrot, Quagga, Raccoon DEFDo statements, Else statements, For statements GHIGeese, Hippos, If statements...
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT