The error message IOError: [Errno 2] No such file or directory: 'words.txt'
means that Python cannot find the file words.txt
at the place where it's looking for it.
Where is Python looking for the file?
If the string passed to open()
looks like an absolute path, Python will look there. 'words.txt'
does not look like an absolute path, so it is treated as a relative path. Relative to what? Other than you might expect, not relative to your python source file, but relative to the current working directory.
If you invoked the script from an interactive shell, you probably know the applicable current working directory. I don't know if that's someone one can/does do when developing with Qpython. But if not, don't worry.
import os
print os.getcwd()
will output the current working directory's path, which should help you figure out where to put your file or how to access it.
Indentation matters in python
That the actual exception's message is output is good for debugging. But as you have an except block, it's probably not what you intended. If you want "Invalid Filename " to be output, you have to fix the indentation of the try block. (fhand = open('words.txt')
must be indented relative to try:
.)
I'm actually a bit surprised this ran at all and you didn't get a message saying IndentationError: expected an indented block
.
Proper exception handling
Only catch what you can (and do) handle correctly
Note that, once the try
block is fixed (see section above), the except
block will catch every exception in it, even if it isn't IOError: [Errno 2] No such file or directory
. This means you'd output "Invalid Filename " even when there's a completely different problem in open
, like running out of RAM to allocate.
So try to catch the specific error you will handle in the except
block.
Use stderr for error messages
With
print >> sys.stderr, "Invalid Filename "
you can print to the standard error stream instead of the standard output stream. This will be useful if your script's standard output is redirected to a file.
Using the user input
You're currently using a hardcoded filename and doing nothing with the name the user has input when prompted Enter a File Name:
. I guess once you're done debugging, you'll replace the hardcoded filename by imp
, which here holds the user input. Be aware that by just substituting it, you will allow users to not just specify a file name, but a file path (absolute or relative to the current working dir) that your script will then access. This might or might not be something you want to permit.