This means that you are successfully catching an error and going to the condition in except
statement and as a result your data is never loaded and the variable data
is never defined. And then when you try to save data to csv, this triggers an error.
What you should do instead is to put your to_csv
statement inside try-except
as well:
import simplejson
import pandas as pd
with open('/tmp/test.json') as f:
try:
data = pd.DataFrame(simplejson.loads(line) for line in f)
data.to_csv('/tmp/data.csv')
except Exception as e:
pass
Also, it is a horrible anti-pattern in Python to do except Exception as e: pass
. This will result in the code that is nigh impossible to debug because you are catching every single error that might happen and not specifically the error you expect to happen. When you do this you should either log the full error stack or print it to console to be aware of what exact error you are catching:
try:
data = pd.DataFrame(simplejson.loads(line) for line in f)
except Exception as e:
err = str(e)
print(err)
Or you should be catching a specific error that you expect to happen here:
try:
data = pd.DataFrame(simplejson.loads(line) for line in f)
except FileNotFoundError:
pass