python - 尝试...否则...除了语法错误

标签 python

我不明白这个...

无法运行此代码,我不知道为什么这是语法错误。


    try:
        newT.read()
        #existingArtist = newT['Exif.Image.Artist'].value
        #existingKeywords = newT['Xmp.dc.subject'].value

    except KeyError:
        print "KeyError"

    else:
        #Program will NOT remove existing values
        newT.read()
        if existingArtist != "" :
            newT['Exif.Image.Artist'] = artistString


        print existingKeywords

        keywords = os.path.normpath(relativePath).split(os.sep)
        print keywords
        newT['Xmp.dc.subject'] = existingKeywords + keywords

        newT.write()
    except:
        print "Cannot write tags to ",filePath

最后一个“except:”出现语法错误。再次...我不知道为什么 python 会抛出语法错误(在这个问题上花了 ~3 小时)。

最佳答案

else 之后不能有另一个excepttryexceptelse block 不像函数调用或其他代码 - 您不能随意混合和匹配它们喜欢。它总是一个特定的顺序:

try:
    # execute some code
except:
    # if that code raises an error, go here
    # (this part is just regular code)
else:
    # if the "try" code did not raise an error, go here
    # (this part is also just regular code)

如果您想要捕获在 else block 期间发生的错误,您将需要另一个 try 语句。像这样:

try:
    ...
except:
    ...
else:
    try:
        ...
    except:
        ...

仅供引用,如果您想捕获在 except block 期间发生的错误,同样适用 - 在这种情况下,您还需要另一个 try 语句,例如这个:

try:
    ...
except:
    try:
        ...
    except:
        ...
else:
    ...

关于python - 尝试...否则...除了语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2792491/

相关文章:

python - 值错误: X has 231 features per sample; expecting 1228

python - 如何添加json库

python - 在Python(最好是py3k)上使用sscanf?

python: 类 super() 的代理对象,在指定类开始 MRO 搜索

python - 属性错误: module 'nltk' has no attribute 'download'

python - 你在连接字符串中使用什么dsn来使用python连接到oracle

python - URL Dispatch 中路由的多个路径

python - MongoDB 在 mongoengine 中使用 OR 子句

python - 学习Pygame,为什么这个 'raindrop'(矩形对象)不会掉落?

python 到 mysql 插入错误