2012-06-24 22 views
13

ho ricevuto un'err "IOError: [Errno 0] errore" con questo programma Python:operazioni sui file 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() 

quello che sembra essere il problema? Questi 2 casi di seguito sono ok:

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() 

e:

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() 

ancora, perché

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

non stampa la dimensione del file, è "A +" l'append-mode ? allora il puntatore del file dovrebbe puntare a EOF?

sto usando Windows 7 e Python 2.7.

+0

Da dove prendi l'errore? Il problema sembra essere che stai cercando di leggere un file aperto in modalità append – Dhara

+0

Inoltre, sei sicuro che text.txt esista? – Dhara

+0

Il tuo codice funziona bene per me. 'tell' restituisce' 0' solo dopo aver aperto il file, ovviamente, perché ti aspetteresti qualcos'altro? –

risposta

10

Python utilizza la funzione fopen di stdio e passa la modalità come argomento. Suppongo che tu usi Windows, dato che @Lev dice che il codice funziona bene su Linux.

Di seguito è dal fopen documentazione delle finestre, questo può essere un indizio per risolvere il tuo 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.

Quindi, la soluzione è quella di aggiungere file.seek() prima della chiamata file.write(). Per accodare fino alla fine del file, utilizzare file.seek(0, 2).

Per riferimento, file.seek funziona nel seguente 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.

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

Come citato da @lvc nei commenti e @Burkhan nella sua risposta, è possibile utilizzare il più recente funzione di apertura da io module. Tuttavia, voglio sottolineare che la funzione di scrittura non funziona esattamente lo stesso in questo caso - è necessario fornire stringhe Unicode come input [Semplicemente prefisso Un u alla stringa nel tuo caso]:

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

Infine, si prega di evitare di usare il nome 'file' come nome di variabile, poiché si riferisce a un tipo predefinito e verrà sovrascritto in modo silenzioso, causando alcuni errori difficili da individuare.

+0

'a +' permette la lettura. –

+0

@LevLevitsky, non ho potuto garantire che dalla documentazione, ma hai ragione, il codice funziona – Dhara

+0

Inoltre, apre i file inesistenti senza errori, anche. –

6

La soluzione è quella di utilizzare open da 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 
Problemi correlati