Python NameError 处理 - 如何捕获异常

Python NameError handling - How to catch exception

在尝试将文件解析为 Pandas DataFrame 时如何捕获 NameError。

代码如下:

try:
    for filename in os.listdir():
        if filename.endswith('.txt'):
            df = pd.read_csv(filename)
            break
except NameError:
    print('No SVP file in directory. Please copy from Survey Online directory')

如果我的文件夹中没有 *.txt 文件,它会抛出我无法捕获的 NameError。它无法归档文件,因此 'df' 未定义。

错误如下:

NameError: name 'df' is not defined

您的代码应该是这样的:

import os

import pandas as pd

try:
    for filename in os.listdir():
        if filename.endswith('.txt'):
            df = pd.read_csv(filename)
            break
except Exception as err:
    print(f'Some error occured -  {err} ')

# write try catch block when you are trying to access the `df` variable when it could be non-existent.
try:
    print(df)
except NameError:
    print('No SVP file in directory. Please copy from Survey Online directory')

输出:

No SVP file in directory. Please copy from Survey Online directory

您使用的逻辑没有多大意义。如果代码出现问题,则会抛出(并捕获)异常。您的代码中没有任何内容会引发异常。如果没有 .txt 个文件,您将永远不会定义 df。如果您尝试访问 df 但它不存在,情况就会不同。例如,试试这个:

for filename in os.listdir():
    if filename.endswith('.txt'):
        df = pd.read_csv(filename)
        break

try:
    df.head()
except NameError:
    print('No SVP file in directory. Please copy from Survey Online directory')

这是有规律可循的。我个人更喜欢它而不是稍后捕获异常,因为它非常清楚代码在做什么。

for filename in os.listdir():
    if filename.endswith('.txt'):
        df = pd.read_csv(filename)
        break
else:
    # your error code here