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 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...
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...
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...
C Programming: Write a program that accepts 2 arguments, an input file and an output file....
C Programming: Write a program that accepts 2 arguments, an input file and an output file. The program is to store in the output file the contents of the input file in reverse. If the input file looks like this: Hello World.\n This is Line 2\n This is the end.\n then the output file should look like this: \n .dne eht si sihT\n 2 eniL si sihT\n .dlroW olleH The main program should look like this: int main(int argc, char...
In c++  write a program. Give the necessary statements to open a file and to confirm that...
In c++  write a program. Give the necessary statements to open a file and to confirm that the file has been successfully opened for writing.
Write a program to perform the following actions: the language is Java – Open an output...
Write a program to perform the following actions: the language is Java – Open an output file named “Assign14Numbers.txt” – Using a do-while loop, prompt the user for and input a count of the number of random integers to produce, make sure the value is between 35 and 150, inclusive. – After obtaining a good count, use a for-loop to generate the random integers in the range 0 ... 99, inclusive, and output each to the file as it is...
Program Requirements: Write a C++ program according to the following requirements: 1.   Open the data file...
Program Requirements: Write a C++ program according to the following requirements: 1.   Open the data file Electricity.txt and read each column into an array (8 arrays total). 2.   Also create 2 arrays for the following: Total Fossil Fuel Energy (sum of all fossil fuels) Total Renewable Energy (sum of all renewable sources) Electricity.txt: Net generation United States all sectors monthly https://www.eia.gov/electricity/data/browser/ Source: U.S. Energy Information Administration All values in thousands of megawatthours Year   all fuels   coal       natural gas   nuclear  ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT