Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Python Error: Writing a program to complete the following: Prompt the user for the name of an input file. Open that file for input. (reading)

Python Error: Writing a program to complete the following:

  • Prompt the user for the name of an input file.
  • Open that file for input. (reading)
  • Read the file using a "for line in a file" loop
  • For each line, o print the line and compute and print the average word length for that line.
  • Close the input file Sample output:

MY CODE IS WRONG AND NEED HELP CORRECTING IT!!!

------------------------------------------------------------------------------------------------------------------------

DESIRED OUTPUT:

Enter input file name: Seasons.txt

Thirty days hath September

5.75

April, June, and November

5.5

All the rest have thirty-one

4.8

Except February, which has twenty-eight.

7.2

-------------------------------------------------------------------------------------------------------------

CODE I HAVE WRITTEN (WRONG):

def main():

# Prompt the user for the name of an input file.

file=input("Enter input file name: ")

# Open file.

infile=open(file, "r")

aLine = infile.readline()

phrase=aLine

# Use split to break phrase into individual strings.

words = phrase.split()

# Define word count

wordCount = len(words)

# Calculate average word count.

for word in words:

sum = 0

avg = 1

ch = len(word)

sum = sum + ch

avg = sum / wordCount

print("A: ",aLine,avg)

aLine = infile.readline()

print("B: ",aLine,avg)

aLine = infile.readline()

print("C: ",aLine,avg)

aLine = infile.readline()

print("D: ",aLine,print(avg))

infile.close()

main()

------------------------------------------------------------------------------------------------------------------------

FILE IS CALLED: "Seasons.txt"

CONTENT:----------------------------------------------------------------------------------------------------------

Thirty days hath September April, June, and November All the rest have thirty-one Except February, which has twenty-eight.

------------------------------------------------------------------------------------------------------------------------

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions