Python:如何进行 if/else 条件判断以读取可能为空的 CSV 文件

huangapple go评论62阅读模式
英文:

python: how to do an if/else to read in a csv that can be empty

问题

我想创建一个try/except或if/else语句根据输入的CSV文件创建数据框架但是输入的CSV文件可能是空的所以如果我使用`pd.read_csv(file_name)`会在CSV文件为空时抛出错误

我该如何做才能实现以下效果
```python
if pd.read_csv(file_name) 成功:
   new_df = pd.read_csv(file_name)
else:
   new_df = pd.DataFrame() # 设置为空数据框架

我之前尝试过:

try:
    new_df = pd.read_csv(file_name)
except:
    new_df = pd.DataFrame() # 设置为空数据框架

但这并没有起作用,因为它总是将new_df设置为空的数据框架,即使CSV文件不为空。

谢谢提前帮助!


<details>
<summary>英文:</summary>

i want to create a try/except or an if/else statement to create dataframes based on an input csv. but it is possible for the input csv to be blank/empty so if i do a blanket `pd.read_csv(file_name)` 
it will throw an error when the csv is empty.

how can i do this so that:

if pd.read_csv(file_name) is successful:
new_df = pd.read_csv(file_name)
else:
new_df = pd.DataFrame() # to set this as an empty data frame


i previously tried:

try:
new_df = pd.read_csv(file_name)
except:
new_df = pd.DataFrame() # to set this as an empty data frame

this did not work because it always set new_df to an empty df even if the csv was not empty

thanks in advance!!!

</details>


# 答案1
**得分**: 2

尝试使用 `pandas.read_csv` 读取空的 CSV 文件会引发 `pandas.errors.EmptyDataError` 异常,因此您可以特定地捕获它:

```python
import pandas as pd

try:
    df = pd.read_csv('my_file.csv')
except pd.errors.EmptyDataError:
    df = pd.DataFrame()
英文:

Trying to read an empty CSV with pandas.read_csv raises a pandas.errors.EmptyDataError exception, so you can catch that specifically

import pandas as pd


try:
    df = pd.read_csv(&#39;my_file.csv&#39;)
except pd.errors.EmptyDataError:
    df = pd.DataFrame()

答案2

得分: 0

你可以用 try/except 捕获异常:

try:
    new_df = pd.read_csv(file_name)
except SomePandasError:  # 用实际的异常替换此处
    new_df = pd.DataFrame()

只有当指定的异常类型被触发时,except 才会发生。如果你用了裸的 try/except 并且总是得到一个空的数据框,这意味着异常 总是 被触发 —— 确保只捕获你预期的异常(即在空的 CSV 上触发的异常),这样如果遇到其他错误,它将像通常一样触发,你可以找出如何修复它。

英文:

You can catch exceptions with try/except:

try:
   new_df = pd.read_csv(file_name)
except SomePandasError:  # replace this with the actual exception
   new_df = pd.DataFrame()

The except will only happen if the specified exception type is raised. If you did a bare try/except and you were always getting a blank dataframe, it means that an exception is always being raised -- make sure to only catch the exception that you expect (i.e. the one raised on an empty CSV) so that if you hit some other error it will raise as normal and you can figure out how to fix it.

huangapple
  • 本文由 发表于 2023年6月9日 03:05:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434978.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定