Python名称错误处理-如何捕获异常

Python名称错误处理-如何捕获异常,python,exception,nameerror,Python,Exception,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

当试图将文件解析为数据帧时,如何捕获名称错误

下面的代码:

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')
NameError: name 'df' is not defined
No SVP file in directory. Please copy from Survey Online directory
如果我的文件夹中没有*.txt文件,它会抛出我无法捕捉的名称错误。它无法归档文件,因此未定义“df”

以下错误:

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')
NameError: name 'df' is not defined
No SVP file in directory. Please copy from Survey Online directory

您的代码应该如下所示:

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')
输出:

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')
NameError: name 'df' is not defined
No SVP file in directory. Please copy from Survey Online directory

你使用的逻辑没有多大意义。如果代码出现问题,将抛出(并捕获)异常。没有任何东西会在代码中引发异常。如果没有
.txt
文件,您将永远不会定义
df
。另一种情况是,如果您试图访问
df
,但它不存在。例如,尝试以下方法:

os.listdir()中文件名的
:
如果filename.endswith('.txt'):
df=pd.read\u csv(文件名)
打破
尝试:
df.head()
除名称错误外:
打印('目录中没有SVP文件。请从在线调查目录中复制')

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

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

显示的
try
块中没有出现
namererror
。您的
try..except
应该在使用它的语句周围。您在哪里使用
df
变量?这是您应该出现的
try catch
部分。