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 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
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...
Write a C++ program that start the assignment by creating a file named pointerTasks.cpp with an...
Write a C++ program that start the assignment by creating a file named pointerTasks.cpp with an empty main function, then add statements in main() to accomplish each of the tasks listed below. Some of the tasks will only require a single C++ statement, others will require more than one. For each step, include a comment in your program indicating which step you are completing in the following statement(s). The easiest way to do this is copy and paste the below...
Write a C++ program that start the assignment by creating a file named pointerTasks.cpp with an...
Write a C++ program that start the assignment by creating a file named pointerTasks.cpp with an empty main function, then add statements in main() to accomplish each of the tasks listed below. Some of the tasks will only require a single C++ statement, others will require more than one. For each step, include a comment in your program indicating which step you are completing in the following statement(s). The easiest way to do this is copy and paste the below...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT