解决TypeError:'file'对象没有属性'__getitem__'

时间:2015-08-17 16:00:15

标签: python database file csv

我正在尝试创建一个文件,其中仅包含文件1上的名称,而不是文件1.我在运行以下代码时出错:

import pandas
import csv
f = pandas.read_csv('hillelclass2019.csv')
g = pandas.read_csv('shabsignup.csv')
for i in range(193): #length of data1
    x = str(f['First Name'][i]) + " " + str(f['Last Name'][i]) #first name + last name
    a = 0 #initial
    for j in range(25): #length of data2
        if g['Name'][j] == x: #if name == name on other sheet, then a == 1
            a == 1
    if a == 0: #if names are not equal 
        with open('noshab.csv', 'a') as f: #write name to file
            wtr = csv.writer(f, delimiter= ',')
            wtr.writerow( [x,i])

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/kz/351q8p011qjc2x4k9srypcqc0000gn/T/tmpf4VgQX.py in <module>()
      5 g = pandas.read_csv('shabsignup.csv')
      6 for i in range(193): #length of data1
----> 7     x = str(f['First Name'][i]) + " " + str(f['Last Name'][i]) #first name + last name
      8     a = 0 #initial
      9     for j in range(25): #length of data2

TypeError: 'file' object has no attribute '__getitem__' 

当我在范围(1)中设置i并且仅运行1次迭代时,代码有效,但不适用于多行。

2 个答案:

答案 0 :(得分:1)

您已将f绑定到循环中的文件对象,因此在一次迭代后它不再指向df,因此f['First Name'][i]file_object['First Name'][i]而不是your_dataframe['First Name'][i]所以它显然失败了:

with open('noshab.csv', 'a') as f: # <- f is now a file object

将名称从f = pandas.read_csv('hillelclass2019.csv')更改为df = pandas.read_csv('hillelclass2019.csv'),并使用df引用代码中的数据框:

df = pandas.read_csv('hillelclass2019.csv')
g = pandas.read_csv('shabsignup.csv')
for i in range(193): #length of data1
    x = str(df['First Name'][i]) + " " + str(df['Last Name'][i]) #first name + last name

另一个注意事项a == 1if g['Name'][j] == x:无效,我认为你的意思是a = 1

答案 1 :(得分:0)

发生错误是因为您尝试像dict一样访问文件实例。

f['First Name']或任何其他密钥访问不适用于文件实例。

错误是指__getitem__函数,随时可以调用它来尝试使用[]索引到对象,通常是字典或类似的键控结构。