What are all the exceptions that can be thrown by pd.read_csv()?
In the example below I am capturing some exception types explicitly and using a generic Exception to catch the others, but what are the others exactly?
Reviewing the documentation for pandas read_csv() I can't see a complete list of exceptions thrown.
In a more general case, what is the recommended practice to determine all of the types of exceptions that can be thrown by any call/library?
import pandas as pd
try:
df = pd.read_csv("myfile.csv")
except FileNotFoundError:
print("File not found.")
except pd.errors.EmptyDataError:
print("No data")
except pd.errors.ParserError:
print("Parse error")
except Exception:
print("Some other exception")
The pandas. read_csv is used to load a CSV file as a pandas dataframe. In this article, you will learn the different features of the read_csv function of pandas apart from loading the CSV file and the parameters which can be customized to get better output from the read_csv function.
Read a CSV File In this case, the Pandas read_csv() function returns a new DataFrame with the data and labels from the file data. csv , which you specified with the first argument.
Read a comma-separated values (csv) file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for IO Tools.
Pandas read_csv() Function. The Pandas read_csv() method reads the specified comma-separated values ( CSV ) file into DataFrame .
You can see all the exceptions in the following file:
Python > 3.8 > lib > python > site-packages > pandas > errors > __init__.py
BTW, the exceptions are:
A complete list and explanation can be found in the pandas source code
If you import pandas
and use the dir
function you can view all exceptions. Exceptions are contained in the pandas.errors
submodule.
In [1]: import pandas as pd
In [2]: ([e for e in dir(pd.errors) if "__" not in e])
Out[2]:
['AbstractMethodError',
'AccessorRegistrationWarning',
'DtypeWarning',
'DuplicateLabelError',
'EmptyDataError',
'IntCastingNaNError',
'InvalidIndexError',
'MergeError',
'NullFrequencyError',
'NumbaUtilError',
'OptionError',
'OutOfBoundsDatetime',
'OutOfBoundsTimedelta',
'ParserError',
'ParserWarning',
'PerformanceWarning',
'UnsortedIndexError',
'UnsupportedFunctionCall']
You can use these for exception handling. As an example, see below
import pandas as pd
import datetime
bad_date = datetime.date(22, 10, 4)
try:
pd.to_datetime(bad_date)
except pd.errors.OutOfBoundsDatetime as e:
# do some error handling here
# or raise the error
print("there was a bad date")
raise e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With