You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Notebook出现未关闭套接字及文件资源警告问题求助

解决Jupyter中csvkit读取文件引发的ResourceWarning问题

问题描述

在Jupyter Notebook中执行安装csvkit并读取train.csv生成DataFrame的代码后,触发ResourceWarning,提示存在未关闭的zmq.Socket及多个文件句柄,错误信息如下:

sys:1: ResourceWarning: unclosed socket <zmq.Socket(zmq.PUSH) at 0x26e1c8709a0>
C:\Users\knnid\anaconda3\lib\site-packages\IPython\utils_process_win32.py:145: ResourceWarning: unclosed file <_io.BufferedWriter name=4>
C:\Users\knnid\anaconda3\lib\site-packages\IPython\utils_process_win32.py:145: ResourceWarning: unclosed file <_io.BufferedReader name=5>
C:\Users\knnid\anaconda3\lib\site-packages\IPython\utils_process_win32.py:145: ResourceWarning: unclosed file <_io.BufferedReader name=6>

执行代码:

!pip install csvkit
import csvkit
import pandas as pd

with open('train.csv', 'r') as file:
    reader = csvkit.DictReader(file)
    data = [row for row in reader]

df = pd.DataFrame(data)

解决方案

1. 改用pandas直接读取CSV(优先推荐)

csvkit的DictReader并未提供比pandas更优的CSV读取能力,而pandas内置的read_csv方法有完善的资源管理机制,可彻底避免这类资源泄漏:

import pandas as pd
df = pd.read_csv('train.csv')

2. 显式关闭csvkit Reader资源

若必须使用csvkit,可在遍历完数据后手动调用close()方法释放资源:

!pip install csvkit
import csvkit
import pandas as pd

with open('train.csv', 'r') as file:
    reader = csvkit.DictReader(file)
    data = [row for row in reader]
    reader.close()  # 显式关闭Reader,释放关联资源

df = pd.DataFrame(data)

3. 升级依赖库版本

这类警告多为IPython或csvkit的已知资源泄漏bug,升级到最新版本通常能修复:

!pip install --upgrade ipython csvkit

4. 临时抑制警告(仅应急使用)

若只是需要隐藏警告而非解决根源问题,可在代码开头添加警告过滤:

import warnings
warnings.filterwarnings("ignore", category=ResourceWarning)

!pip install csvkit
import csvkit
import pandas as pd

with open('train.csv', 'r') as file:
    reader = csvkit.DictReader(file)
    data = [row for row in reader]

df = pd.DataFrame(data)

内容的提问来源于stack exchange,提问作者augusta26

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 05:19:57