[尝试将文件解析为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
您使用的逻辑没有多大意义。如果代码出了问题,则会引发(并捕获)异常。没有什么会在您的代码中引发异常。如果没有.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')
您的代码应为:
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
有一种模式。我个人更喜欢它稍后再捕获异常,因为它很清楚代码在做什么。
for filename in os.listdir():
if filename.endswith('.txt'):
df = pd.read_csv(filename)
break
else:
# your error code here