2012-04-17 14 views
5

Tengo una tarea para una clase de Python y me encuentro con un error que no entiendo. Ejecución de Python V3.2.2 IDLE en Windows 7.AttributeError: el objeto 'tuple' no tiene ningún atributo 'write'

continuación es donde el problema está ocurriendo:

#local variables 
number=0 
item='' 
cost='' 

#prompt user how many entries 
number=int(input('\nHow many items to add?: ')) 

#open file 
openfile=('test.txt','w') 

#starts for loop to write new lines 
for count in range(1,number+1): 
    print('\nFor item #',count,'.',sep='') 
    item=input('Name: ') 
    cost=float(input('Cost: $')) 

    #write to file 
    openfile.write(item+'\n') 
    openfile.write(cost+'\n') 

#Display message and closes file 
print('Records written to test.txt.',sep='') 
openfile.close 

Este es el error que estoy recibiendo:

Traceback (most recent call last): File "I:\Cent 110\test.py", line 19, in openfile.write(item+'\n')
AttributeError: 'tuple' object has no attribute 'write'

+2

Debe retirar la [ '' comunicado with''] (http://docs.python.org/reference/compound_stmts.html#the-with-statement) para abrir archivos - que le significa don no tiene que cerrarlos manualmente, y funciona correctamente incluso bajo excepciones. –

+0

@Lattyware: Definitivamente revisaré eso. Gracias por el aporte. – dhc

Respuesta

7

Te estás perdiendo la open.

openfile = open('test.txt','w') 

Y al final hay parens falta cuando intenta cerrar el archivo

openfile.close() 

Edición: Acabo de ver otro problema.

openfile.write(str(cost)+'\n') 
+0

openfile = open ('test.txt', 'w') está allí. Gracias también :) – dhc

+3

El _open_ no está en el código que publicaste. – Matthias

+0

Gracias por tomar el paréntesis final. Lo extrañé por completo. Sin embargo, eso no solucionó mi problema. :( – dhc

Cuestiones relacionadas