为什么这个python代码不会打开文件?

时间:2015-10-03 18:37:03

标签: python

当我运行此代码时,它会提示输入文件名,并询问我是否输入文件的路径,或者拖放,它将运行代码'File cannot be opened'的除部分,但它将永远不会运行fuse = open(fname)或该计划的其余部分。

这是完整的程序:

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

任何可能出错的想法?​​

当我在没有尝试的情况下运行它,除了从命令行看到错误,这是我得到的消息:

输入文件名:“C:\ Users \ Gonzalez Cocoma \ Documents \ Python \ Programs \ mbox-short.txt” Traceback(最近一次调用最后一次):   文件“C:\ Users \ Gonzalez Cocoma \ Documents \ Python \ Programs \ Spamaverage.py”,第2行,in     fuse = open(fname) IOError:[Errno 22]无效模式('r')或文件名:'“C:\ Users \ Gonzalez Cocoma \ Documents \ Python \ Programs \ mbox-short.txt”'

1 个答案:

答案 0 :(得分:1)

fname不是有效档案。

从提示符开始:

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

如果您尝试打开它,您将获得例外:

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

您可以捕获异常并打印其值:

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

文件名无效的原因是您包含了引号。

错误消息显示字符串'“path / to / file.txt”'。它应该显示'path / to / file.txt':

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

应该是:

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