Question

For Python-3 I need help with First creating a text file named "items.txt" that has the...

For Python-3

I need help with

First creating a text file named "items.txt" that has the following data in this order: Potatoes Tomatoes Carrots.

Write a python program that

1. Puts this as the first line... import os

2. Creates an empty list

3. Defines main() function that performs the tasks listed below when called.

4. Put these two lines at the top of the main function... if os.path.exists("costlist.txt"): os.remove("costlist.txt")

Note: This removes the "costlist.txt" file, if it exists.

5. Display "Assignment 6"

6. Prompts the user to enter a file name.

a. If the file name entered is "end" then end the program.

b. If the file name is "items.txt", open the file for reading, replace all the newline characters with an empty string, and add all of the items from the file to the list that was defined in step #2

c. If a FileNotFoundError exception occurs, display a message that lets the user know the file was not found and gives them a chance to try it again.

7. Sort the list.

8. For each element in the list, prompt the user to enter the price for the element, e.g. How much should Carrots cost? Convert the number entered into a float.

a. If the number entered does not convert properly into a float, and gets a ValueError exception, then display a couple error messages in the following format... You entered an invalid float that could not convert string to float: 'ss' Skipping to the next item after (element) ... and then prompt the user to enter the price of the next element from the list.

b. If the number does convert properly to a float then create a string variable with the following format... (element) have a cost of (cost) dollars ... and open the "costlist.txt" file for appending and write the string created to a line in the file.

9. Display "Cost List"

10. Display each line from the "costlist.txt" file

11. Display "Program End"

Below is a example of how the program might run, the program should run in a similar manner no matter what names and age are entered.

Example Run #1:

Assignment 6

Enter file name end

Program Ended

Example Run #2:

Assignment 6

Enter file name items.txt

How much should Carrots cost? ss

You entered an invalid float that could not convert string to float: 'ss' Skipping to the next item after Carrots

How much should Potatoes cost? 77

How much should Tomatoes cost? 44

Cost List:

Potatoes have a cost of 77.0 dollars

Tomatoes have a cost of 44.0 dollars

Program End Example

Run #3:

Assignment 6

Enter file name aa.txt

Could not find file named aa.txt. Please Try Again

Enter file name items.txt

How much should Carrots cost? 11.23

How much should Potatoes cost? 4.77

How much should Tomatoes cost? 7.99

Cost List:

Carrots have a cost of 11.23 dollars

Potatoes have a cost of 4.77 dollars

Tomatoes have a cost of 7.99 dollars

Program End

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python Program:

import os

def main():
   """ Main function """
   # Empty items list
   items = []
  
   if os.path.exists("costlist.txt"):
       os.remove("costlist.txt")
      
   print("Assignment 6")

   loop = True
   # Loop till user enters valid file name
   while loop:  
       # Reading file name
       fName = input("Enter file name: ")
      
       try:      
           # Checking file name
           if fName.lower() == "end":
               print("Program Ended")
               return
          
           else:
               # Opening file for reading
               fp = open(fName, "r")
               loop = False
               # Replace all the newline characters with an empty string  
               for line in fp:
                   line = line.strip()
                   # Adding items to list
                   for item in line.split(' '):
                       items.append(item)
              
               # Closing file
               fp.close()
              
               # Sorting items
               items.sort()
              
               # Opening file for appending
               opFile = open("costlist.txt", "w")
                  
               # Reading cost
               for item in items:
                   try:  
                       cost = float(input("How much should " + item + " cost? "))
                       # Writing to file
                       opFile.write(item + " have a cost of " + str(cost) + " dollars\n")
                   except ValueError:
                       print("You entered an invalid float that could not convert string to float: 'ss' Skipping to the next item after " + item + "\n")
              
               # Closing output file
               opFile.close()
              
               print("Cost List: ")
              
               # Reading and printing data from cost file
               ipFile = open("costlist.txt", "r")
              
               # Reading and printing text
               for line in ipFile:
                   line = line.strip()
                   print(line)
                  
               # Closing input file
               ipFile.close()
              
               print("Program End")
          
       except FileNotFoundError:
           print("Could not find file named " + fName + ". Please Try Again")
              
              
              
# Calling main function
main()

______________________________________________________________________________________________________

Sample Run:

______________________________________________________________________________________________________

Code Screenshot:

Add a comment
Know the answer?
Add Answer to:
For Python-3 I need help with First creating a text file named "items.txt" that has the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need help with the code for this assignment. Python Assignment: List and Tuples We will do...

    Need help with the code for this assignment. Python Assignment: List and Tuples We will do some basic data analysis on information stored in external files. GirNames.txt contains a list of the 200 most popular names given to girls born in US from year 2000 thru 2009: (copy link and create a txt file): https://docs.google.com/document/d/11YCVqVTrzqQgp2xJqyqPruGtlyxs2X3DFWn1YUb3ddw/edit?usp=sharing BoyNames.txt contains a list of the 200 most popular names given to boys born in US from year 2000 thru 2009 (copy link and create...

  • Create a python code named LetterCount with a text file named words.txt that contains at least...

    Create a python code named LetterCount with a text file named words.txt that contains at least 100 words in any format - some words on the same line, some alone (this program involves no writing so you should not be erasing this file). Then create a program in the main.py that prompts the user for a file name then iterates through all the letters in words.txt, counting the frequency of each letter, and then printing those numbers at the end...

  • Write a java netbeans program. Project Two, Super Bowl A text file named “SuperBowlWinners.txt” contains the...

    Write a java netbeans program. Project Two, Super Bowl A text file named “SuperBowlWinners.txt” contains the names of the teams that won the Super Bowl from 1967 through 2019. Write a program that repeatedly allows a user to enter a team name and then displays the number of times and the years in which that team won the Super Bowl. If the team entered by the user has never won the Super Bowl, report that to the user instead. For...

  • I need help building code in python for this: Create a program that: Creates a sales...

    I need help building code in python for this: Create a program that: Creates a sales receipt, displays the receipt entries and totals, and saves the receipt entries to a file Prompt the user to enter the Item Name Item Quantity Item Price Display the item name, the quantity, and item price, and the extended price (Item Quantity multiplied by Item Price) after the entry is made Save the item name, quantity, item price, and extended price to a file...

  • Need some help on this Python Problem called "unique words" the text.txt file can be any...

    Need some help on this Python Problem called "unique words" the text.txt file can be any .txt file with words in it. Write a program that opens a specified text file and then displays the number of unique words in the text file after stripping all the white spaces, comma, and the punctuation marks and list of all the unique words found in the file. The list should be sorted in alphabetical order. The program should handle the ‘file not...

  • Pig Latin Translator in Java The goal here is to read in the characters stored in a text file and create a second text file that contains the original text but with every word converted to “Pig-Latin....

    Pig Latin Translator in Java The goal here is to read in the characters stored in a text file and create a second text file that contains the original text but with every word converted to “Pig-Latin.” The rules used by Pig Latin are as follows: • If a word begins with a vowel, just as "yay" to the end. For example, "out" is translated into "outyay". • If it begins with a consonant, then we take all consonants before...

  • Write you code in a class named HighScores, in file named HighScores.java. Write a program that...

    Write you code in a class named HighScores, in file named HighScores.java. Write a program that records high-score data for a fictitious game. The program will ask the user to enter five names, and five scores. It will store the data in memory, and print it back out sorted by score. The output from your program should look approximately like this: Enter the name for score #1: Suzy Enter the score for score #1: 600 Enter the name for score...

  • Python: The attached text file: https://drive.google.com/open?id=1Hcj4Ey4NbKHn5-vyF-foR3iny0aX8y1...

    Python: The attached text file: https://drive.google.com/open?id=1Hcj4Ey4NbKHn5-vyF-foR3iny0aX8y1c Unique Words Write a program that opens a specified text file and then displays the number of unique words in the text file after stripping all the white spaces, comma, and the punctuation marks and a list of all the unique words found in the file. The list should be sorted in alphabetical order. The program should handle the ‘file not found’ error. Store each word as an element of list. Be sure not...

  • Must be done in python and using linux mint Write a program to create a text...

    Must be done in python and using linux mint Write a program to create a text file which contains a sequence of test scores. Each score will be between 0 and 100 inclusive. There will be one value per line, with no additional text in the file. Stop adding information to the file when the user enters -1 The program will first ask for a file name and then the scores. Use a sentinel of -1 to indicate the user...

  • I need help in Python. This is a two step problem So I have the code...

    I need help in Python. This is a two step problem So I have the code down, but I am missing some requirements that I am stuck on. Also, I need help verifying the problem is correct.:) 7. Random Number File Writer Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 500. The application should let the user specify how many random numbers the file...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT