Luis Gonzalez
Luis Gonzalez

Reputation: 105

Why won't this python code open the file?

When I run this code it prompts for the file name, and regardles whether I enter the path to the file, or drag and drop, it will run the except part of the code 'File cannot be opened' but it will never run fuse = open(fname) or the rest of the program.

Here is the complete program:

fname = raw_input('Enter file name: ')
try:
    fuse = open(fname)
except:
    print 'File cannot be opened'
    raw_input('Press enter to quit')
count = 0
total = 0
for line in fuse:
    if line.notstartswith('X-DSPAM-Confidence:'): continue
    elif line.startswith('X-DSPAM-Confidence:'):
    count = count + 1
    vpos = line.find(' ')
    addv = line[vpos:]
    addv = float(addv)
    total = total + addv

print total/count

Any ideas of what could be wrong?

When I run it without the try and except from the command line to see the error, this is the message I get:

Enter file name: "C:\Users\Gonzalez Cocoma\Documents\Python\Programs\mbox-short.txt" Traceback (most recent call last): File "C:\Users\Gonzalez Cocoma\Documents\Python\Programs\Spamaverage.py", line 2, in fuse = open(fname) IOError: [Errno 22] invalid mode ('r') or filename: '"C:\Users\Gonzalez Cocoma\Documents\Python\Programs\mbox-short.txt"'

Upvotes: 1

Views: 2269

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

fname isn't a valid file.

From the prompt:

>>> import os
>>> fname = 'invalid-filename.txt'
>>> os.path.isfile(fname)
False

If you try and open it you will get an exception:

>>> open(fname)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'invalid-filename.txt'

You can catch the exception, and print its value:

>>> try:
...     open(fname):
... except IOError as error:
...     print e
[Errno 2] No such file or directory: 'invalid-filename.txt'

The reason the filename wasn't valid is that you'd included quotes.

The error message shows a string '"path/to/file.txt"'. It should show 'path/to/file.txt':

IOError: [Errno 22] invalid mode ('r') or filename:
    '"C:\Users\Gonzalez Cocoma\Documents\Python\Programs\mbox-short.txt"'

Should be:

IOError: [Errno 22] invalid mode ('r') or filename:
    'C:\Users\Gonzalez Cocoma\Documents\Python\Programs\mbox-short.txt'

Upvotes: 1

Related Questions