找不到Python文件错误处理

时间:2015-04-13 19:16:09

标签: python python-3.x

import csv
try:
    with open('test.xlsx',newline='') as csvfile:
        except errno.ENOENT
            print("opps !! no such file")
        dialect = csv.Sniffer().sniff(csvfile.read(1024))
        csvfile.seek(0)
        reader = csv.reader(csvfile, dialect)
        for row in reader:
            print(row)

我得到的错误

  File "<ipython-input-59-b3b9b540a1d8>", line 4
    except errno.ENOENT
         ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:1)

您需要将except块放在与try块相同的级别,并添加一个冒号,并使用正确的异常:

try:
    with open('test.xlsx',newline='') as csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(1024))
        csvfile.seek(0)
        reader = csv.reader(csvfile, dialect)
        for row in reader:
            print(row)
except FileNotFoundError:
    print("Oops! No such file")

如果您只想捕获open()调用并且不在with处理程序中包含try..except块的其余部分,则需要单独打开文件,然后with块中使用它:

try:
    csvfile = open('test.xlsx',newline='')
except FileNotFoundError:
    print("Oops! No such file")

else:
    with csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(1024))
        csvfile.seek(0)
        reader = csv.reader(csvfile, dialect)
        for row in reader:
            print(row)

请注意,errno.ENOENT不是捕获的有效异常,它只是一个常量。我用FileNotFoundError exception代替了;它是OSError的子类,当您尝试打开的文件未找到时,它会被抛出。