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
答案 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
的子类,当您尝试打开的文件未找到时,它会被抛出。