1
使用我在Python 2編寫的函數中,我試圖串連CSV文件:AttributeError的:「_io.TextIOWrapper」對象有沒有屬性「下一個」
def concat_csv():
"""
A function to concatenate the previously wrangled csv files in current working dir
"""
with open('2017_oldnew.csv', 'a') as f_out:
# First file
with open('old.csv') as f_read:
for line in f_read:
f_out.write(line)
# Second file
with open('new.csv') as f_read:
f_read.next()
for line in f_read:
f_out.write(line)
然而,運行此Python 3裏給了我一個錯誤消息:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-110-a5a430e1b905> in <module>()
1 # Concatenate the files
----> 2 concat_csv()
<ipython-input-109-9a5ae77e9dd8> in concat_csv()
10 # Second file
11 with open('new.csv') as f_read:
---> 12 f_read.next()
13 for line in f_read:
14 f_out.write(line)
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
更具體地說,迭代器有一個名爲'__next__'的方法,而不是'next',當迭代器被傳遞給'next'函數時被調用。這使它符合其他協議(例如'len'調用'__len__'等)。 – chepner
注意:[next函數存在於2.6及更高版本中](https://docs.python.org/2/library/functions.html#next),因此您可以在2.6+和3上使用此代碼。 X。從2到3的實際更改是,特殊方法的名稱從'next'更改爲'__next__'(以匹配其他特殊方法,並避免如果next作爲方法有意義但不會導致問題,但是您的類不是迭代器)。使用'next'功能文件來改變這個變化;它在兩個版本上都能正常工作。 – ShadowRanger