AttributeError: '_csv.reader' object has no attribute 'next' 我在使用pyhon3.4运行以下代码时报错:AttributeError:

本文介绍了一种在Python中使用csv模块读取CSV文件时遇到的AttributeError异常及其解决方案,包括如何正确地调用next()方法跳过文件头,并确保文件以正确的模式打开。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


AttributeError: '_csv.reader' object has no attribute 'next'

我在使用pyhon3.4运行以下代码时报错:AttributeError: '_csv.reader' object has no attribute 'next'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import  csv
import  numpy as np
with open ( 'C:/Users/Administrator/Desktop/data/titanic.csv' , 'rb' ) as csvfile:
     titanic_reader =  csv.reader(csvfile, delimiter = ',' , quotechar =  '"' )
     # Header contains feature names
     row =  titanic_reader. next ()
     feature_names =  np.array(row)
     
     # Load dataset, and target classes
     titanic_X, titanic_y =  [], []
     for  row in  titanic_reader:
         titanic_X.append(row)
         titanic_y.append(row[ 2 ]) #The target value is "survived"
     titanic_X =  np.array(titanic_X)
     titanic_y =  np.array(titanic_y)

解决方案:

For version 3.2 and above

Change: csv_file_object.next()

To: next(csv_file_object)

then I get another error:

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

Edit: Figured it out needed to change rb to rt

Finally, it works.

 

REF.

[1]https://www.kaggle.com/c/titanic/forums/t/4937/titanic-problem-with-getting-started-with-python


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值