1

I'm a beginner in python & am having some problems with the structure of my homework assignment; my assignment is: "Write a program that asks the user for a filename, opens the file and reads through the file just once before reporting back to the user the number of characters (including spaces and end of line characters), the number of words, and the number of lines in the file.

If the user enters the name of a file that doesn't exist, your program should give her as many tries as she needs in order to type a valid filename. Obtaining a valid filename from the user is a common operation, so start by writing a separate, reusable function that repeatedly asks the user for a filename until she types in a file that your program is able to open." And, I didn't start that way (& now I'm wondering if with the way I've structured it with "with/as", there's a way to even do that but my problem right now is getting it to go back into the try section of code after the error is thrown (I missed the class where this was explained so I've only ever read about this so I Know I'm not doing something right). I can get it to work as long as it's a filename that exists, if it's not, it prints nothing to the screen. Here's my code:

filename = input("please enter a file name to process:")



lineCount = 0
wordCount = 0
charCount = 0
try:

    with open(filename, 'r') as file:
        for line in file:
            word = line.split()
            lineCount = lineCount + 1
            wordCount = wordCount + len(word)
            charCount = charCount + len(line)

    print("the number of lines in your file is:", lineCount)
    print("the number of words in your file is", wordCount)
    print("the number of characters in your file is:", charCount)

except OSError:

    print("That file doesn't exist")
    filename = input("please enter a file name to process:")

And, I'm not sure what I should do- if I should scrap this whole idea for a simple try: open(filename, 'r') / except: function of it=f there's anyway to salvage this.

So, I thought to fix it this way:

def inputAndRead():
"""prompts user for input, reads file & throws exception"""
filename = None
    while (filename is None):
        inputFilename = input("please enter a file name to process")
        try:
            filename = inputFilename
            open(filename, 'r')
        except OSError:
            print("That file doesn't exist")
    return filename



inputAndRead()

lineCount = 0
wordCount = 0
charCount = 0

with open(filename, 'r') as file:
for line in file:
    word = line.split()
    lineCount = lineCount + 1
    wordCount = wordCount + len(word)
    charCount = charCount + len(line)

print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)

But, I'm getting error: NameError: name 'file' is not defined

KindeR66
  • 37
  • 2
  • 3
  • 10
  • You need an outer `while` loop so that it repeats the code on failure. See http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – roganjosh Mar 01 '17 at 08:18
  • Possible duplicate of [How to make a script wait within an iteration until the Internet connection is reestablished?](http://stackoverflow.com/questions/42344303/how-to-make-a-script-wait-within-an-iteration-until-the-internet-connection-is-r) – Abhishek J Mar 01 '17 at 08:20
  • Why dont you use os.path.exists() to check if file is present instead of relying on exception thrown by open. – saurabh baid Mar 01 '17 at 08:23
  • @roganjosh Didn't see your answer.. just a min taking mine out.. – Abhishek J Mar 01 '17 at 08:24
  • @roganjosh haha true.. – Abhishek J Mar 01 '17 at 08:26
  • thanks @roganjosh - actually that question helped me the most in explaining the structure... – KindeR66 Mar 01 '17 at 12:21

2 Answers2

1

I would reorganize this code so that the file is opened in a loop. No matter how many times the user enters an invalid filename, the code will just ask for a new one and try again.

lineCount = 0
wordCount = 0
charCount = 0

f = None
while f is None:
    filename = input("please enter a file name to process:")
    try:
        f = open(filename)
    except OSError:
        print("That file doesn't exist")

for line in file:
    word = line.split()
    lineCount = lineCount + 1
    wordCount = wordCount + len(word)
    charCount = charCount + len(line)

print("the number of lines in your file is:", lineCount)
print("the number of words in your file is", wordCount)
print("the number of characters in your file is:", charCount)
Nick Frost
  • 490
  • 2
  • 12
-1

Write an infinite loop while True. When the file name is correct, at the end of the try, add a break.

Glad that helps

porthunt
  • 484
  • 1
  • 5
  • 12