Python NameError处理-如何捕获异常[关闭]

问题描述 投票:0回答:3

[尝试将文件解析为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
python exception nameerror
3个回答
0
投票

您使用的逻辑没有多大意义。如果代码出了问题,则会引发(并捕获)异常。没有什么会在您的代码中引发异常。如果没有.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')

0
投票

您的代码应为:

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

0
投票

有一种模式。我个人更喜欢它稍后再捕获异常,因为它很清楚代码在做什么。

for filename in os.listdir():
    if filename.endswith('.txt'):
        df = pd.read_csv(filename)
        break
else:
    # your error code here
© www.soinside.com 2019 - 2024. All rights reserved.