Question

In: Computer Science

PYTHON. Tasks: Create and test the openFileReadRobust() function to open file (for reading) whose name is...

PYTHON.

Tasks:

  1. Create and test the openFileReadRobust() function to open file (for reading) whose name is provided from the standard input (keyboard) – the name is requested until it is correct
  2. Create and test the openFileWriteRobust () function to open file (for writing) whose name is provided from the standard input (keyboard) – the name is requested until is correct
  3. Extend the program to count number of characters, words and lines in a file as discussed in the classby including openFileReadRobust() and openFileWriteRobust () functions
  4. Create simple tallying program to input sequence of integers (each integer 0-100) from a file (name to be entered from the keyboard using openFileReadRobust() function), compute the tally sheet discarding all bad data. Display the discarded bad data on the screen.
  5. Write the content of the tally sheet (write only non-zero counts of numbers – numbers that are in the input file) to a standard output (the shell window).
  6. Extend the program to write the content of the tally sheet (write only non-zero counts of numbers – numbers that are in the input file) to a file (name to be entered from the keyboard). Display the content of the file on the screen.

Assume the content of the file myData1.txt:

5

100

111

OK

55

5

55

5

The interaction of your program should be displayed in the Shell window similarly as shown below:

Task 1

What is the input file name?

myData.txt

This file cannot be opened

What is the input file name?

myData1.txt

Task 2

What is the output file name?

myResults1.txt

Task 3

The number of characters is: 15

The number of words is: 8

The number of lines is: 8

Task 4

Discarded bad data: 111, OK

Task 5

The tally sheet based on your input file is:

Number of 5’s: 3

Number of 55’s: 2

Number of 100’s: 1

Task 6

The tally sheet written to the file: myResults1.txt

Copy of the content of the file myResults1.txt is:

Number of 5’s: 3

Number of 55’s: 2

Number of 100’s: 1

Solutions

Expert Solution

from collections import Counter
import collections

#method to open read file
def openFileReadRobust():
#takinf user input
file_name = input('What is the input file name?\n');
try:
#will throw an exception if file not found
f = open(file_name, 'r')
#returning file name
return file_name
except:
print('This file cannot be opened')
openFileReadRobust()

#method for output file
def openFileWriteRobust():
file_name = input('What is the output file name?\n');
try:
#will throw an exception if file not found
f = open(file_name, 'w')
return file_name
except:
print('This file cannot be opened')
openFileWriteRobust()

#method countData
def countData(file):
data = file.readlines()
  
words = 0
charac = 0
#counting lines, words and characters from the file
for line in data:
s = line.strip()
words += (s.count(' ') + 1)

for char in s:
if char is not ' ':
charac += 1
print("The number of characters is:", charac)
print("The number of words is:", words)
print("The number of lines is:", len(data))

#method to chgeck the data and discard the data
def discardData(file):
data = file.readlines()

ans = []
disc = []
for line in data:
s = line.strip()
if s.isdigit():
a = int(s)
if a >= 0 and a <= 100:
ans.append(a)
else:
disc.append(s)
else:
disc.append(s)

print("Discarded bad data:", ", ".join(disc))
  
return sorted(ans)

#method to print the data
def printData(counter):
s = []
print('The tally sheet based on your input file is:')
for k, v in counter.items():
s.append('Number of '+ str(k)+ "'s: "+ str(v))
return s

def main():
print('Task 1')
inpFile = openFileReadRobust()

print('Task 2')
outFile = openFileWriteRobust()

print('Task 3')
countData(open(inpFile))

print('Task 4')
ans = discardData(open(inpFile))

print('Task 5')
count = dict(Counter(ans))
od = collections.OrderedDict(sorted(count.items()))
s = printData(od)
print("\n".join(s))
  

print('Task 6')
open(outFile, 'w').writelines(s)
print('Copy of the content of the file myResults1.txt is:')
print("\n".join(s))
  
  
main()

IF THERE IS ANYTHING THAT YOU DO NOT UNDERSTAND THEN PLEASE MENTION IT IN THE COMMENTS SECTION


Related Solutions

Please Use Python 3.The Problem: Read the name of a file and then open it for...
Please Use Python 3.The Problem: Read the name of a file and then open it for reading. Read the name of another file and then open it for output. When the program completes, the output file must contain the lines in the input file, but in the reverse order. • Write the input, output, and the relationship between the input and output. • Develop the test data (A single test will be alright). Make the input file at least 3...
Python - files: find a solution for each following: -Open the file hostdata.txt for reading. -Store...
Python - files: find a solution for each following: -Open the file hostdata.txt for reading. -Store four file objects corresponding to the files winter2003.txt , spring2003.txt, summer2003.txt, and fall2003.txt in the variables winter, spring, summer, and fall (respectively), and open them all for reading. -Write a statement to open the file yearsummary.txt in a way that erases any existing data in the file. -Use the file object output to write the string "3.14159" to a file called pi. -A file...
python Create a new file name condition_quiz.py. Add a comment with your name and the date....
python Create a new file name condition_quiz.py. Add a comment with your name and the date. Prompt the user to enter the cost. Convert the input to a float. Prompt the user for a status. Convert the status to an integer Compute the special_fee based on the status. If the status is 0, the special_fee will be 0.03 of the cost. Else if the status is 1, the special_fee will be 0.04 of the cost. Else if the status is...
Write a Python program that uses function(s) for writing to and reading from a file: a....
Write a Python program that uses function(s) for writing to and reading from a file: a. Random Number File Writer Function Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file. b. Random Number File Reader Function Write another function that reads the random numbers...
Using Python, create a function whose inputs are two matrices and whose output is the element...
Using Python, create a function whose inputs are two matrices and whose output is the element wise product of the two matrices.
Create a Word file containing the following: The full name of the “test subject” The test...
Create a Word file containing the following: The full name of the “test subject” The test subject is a person, not yourself, who can say the names of the products. The best test subject is one who is adamant about being an expert who can distinguish brand A from B. You cannot be the test subject because you generate the sequence, and the test subject cannot see it for an unbiased test. Pets and babies are not allowed as they...
​​​​Python Create a new file named compute_cost.py. Write your name and date in a comment. Create...
​​​​Python Create a new file named compute_cost.py. Write your name and date in a comment. Create a variable named base_fee and set the value to 5.5. Prompt the user for the zone. The zones can be an integer value from 1 to any value for the zone. Convert the zone to an integer. Display the zone on the SenseHat with a scroll speed of 0.3, make the text blue, and the background yellow. Scroll "The zone is " and the...
PYTHON. Create a function that accepts a filename where in each line there is a name...
PYTHON. Create a function that accepts a filename where in each line there is a name of a type of bird. use a python dictionary in order to count the # of time each bird appears. (1 line = 1 appearance) Loop over your dict. to print each species and the # of times it was seen in the file once all lines have been counted. return dictionary containing count the filename opens this: blackbird canary hummingbird canary hummingbird canary...
Python. Create a function that receives the name of an auto maker and returns a slice...
Python. Create a function that receives the name of an auto maker and returns a slice of the dataframe with the cars from that auto maker. For instance, it may receive 'ford' and return a slice with all the cars produced by 'ford' meaning they have 'ford' in their name. Call the function for 'ford' to see if it works properly. Hint: You may create a list comprehension producing a list of all the index labels that include the auto-maker's...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns:...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns: None Description : You want to see what order the items of a particular category in your file would be in if you sorted them by rating. Given a file, a category of clothing, and an order boolean (True for ascending order, False for descending order), create a function that writes a file called “sorted_items.csv” that includes all of the items in the specified...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT