Home > Net >  Program to read a file and output number of character, words & lines
Program to read a file and output number of character, words & lines

Time:05-05

I have been working on this program where a user inputs a file name and the program sorts through the file and outputs total number of words, characters & lines. my program works but I need to alter it to remove a line so the user can input the file name for themselves.

I need to alter the second line of code with the comment and remove the hard fixed file location so a user can input file name themselves.

see below my code.

f1 = open(input("Source file name: "))
lines = [line for line in open('P4_v1.txt')] # i want to remove this line to only include user input
words = sum( len(l.split()) for l in lines)
letters = sum( len(l) for l in lines)
print ("Characters: ",letters)
print ("Words: ",words)
print ("Lines: ",len(lines))

the output required

Source file name: P4_v1.txt
Characters:  2208
Words:  420
Lines:  11

thanks

CodePudding user response:

We need to use error handling because the user input may not be a valid file name.

fileName = input("Source file name: ")
f1 = open(fileName)
try:
    lines = [line for line in f1 ] 
    words = sum( len(l.split()) for l in lines)
    letters = sum( len(l) for l in lines)
    print ("Characters: ",letters)
    print ("Words: ",words)
    print ("Lines: ",len(lines))
except IOError:
     print("Error: ", fileName," does not appear to exist.")
  • Related