2012-06-24 15 views
13

tengo una err "IOError: [Errno 0] Error" con este programa Python:operaciones de archivo de Python

from sys import argv 
file = open("test.txt", "a+") 
print file.tell() # not at the EOF place, why? 
print file.read() # 1 
file.write("Some stuff will be written to this file.") # 2 
# there r some errs when both 1 & 2 
print file.tell() 
file.close() 

lo que parece ser el problema? Estos 2 casos por debajo están bien:

from sys import argv 
file = open("test.txt", "a+") 
print file.tell() # not at the EOF place, why? 
# print file.read() # 1 
file.write("Some stuff will be written to this file.") # 2 
# there r some errs when both 1 & 2 
print file.tell() 
file.close() 

y:

from sys import argv 
file = open("test.txt", "a+") 
print file.tell() # not at the EOF place, why? 
print file.read() # 1 
# file.write("Some stuff will be written to this file.") # 2 
# there r some errs when both 1 & 2 
print file.tell() 
file.close() 

aún, ¿por qué

print file.tell() # not at the EOF place, why? 

no imprime el tamaño del archivo, es "+ a" append-mode ? entonces el puntero del archivo debe apuntar a EOF?

uso Windows 7 y Python 2.7.

+0

¿Dónde se obtiene el error? El problema parece ser que estás tratando de leer un archivo abierto en el modo agregar – Dhara

+0

Además, ¿estás seguro de que text.txt existe? – Dhara

+0

Tu código funciona bien para mí. 'tell' devuelve' 0' justo después de abrir el archivo, por supuesto, ¿por qué esperarías algo más? –

Respuesta

10

Python usa la función fopen de stdio y pasa el modo como argumento. Supongo que usas Windows, ya que @Lev dice que el código funciona bien en Linux.

Lo siguiente es de la documentación fopen de las ventanas, esto puede ser una pista para resolver su problema:

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

Por lo tanto, la solución es añadir file.seek() antes de la llamada file.write(). Para agregar al final del archivo, use file.seek(0, 2).

Para su referencia, file.seek funciona del siguiente modo:

To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

[referencia: http://docs.python.org/tutorial/inputoutput.html]

Como se ha mencionado por @lvc en los comentarios y @Burkhan en su respuesta, puede utilizar la más reciente abrir función desde el io module. Sin embargo, quiero señalar que la función de escritura no funciona exactamente igual en este caso - es necesario proporcionar cadenas Unicode como entrada [Simplemente prefijo A u a la cadena en su caso]:

from io import open 
fil = open('text.txt', 'a+') 
fil.write('abc') # This fails 
fil.write(u'abc') # This works 

Finalmente, evite usar el nombre 'archivo' como nombre de variable, ya que se refiere a un tipo incorporado y se sobrescribirá silenciosamente, lo que ocasionará algunos errores difíciles de detectar.

+0

'a +' permite leer. –

+0

@LevLevitsky, no pude asegurarlo de la documentación, pero tiene razón, el código funciona – Dhara

+0

Además, abre archivos inexistentes sin ningún error, también. –

6

La solución es utilizar open de io

D:\>python 
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on 
win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> f = open('file.txt','a+') 
>>> f.tell() 
0L 
>>> f.close() 
>>> from io import open 
>>> f = open('file.txt','a+') 
>>> f.tell() 
22L 
Cuestiones relacionadas