OVH Cloud OVH Cloud

End of file detection

1 réponse
Avatar
Pierrot
Bonjour,
Je débute en Python. Je souhaite lire un fichier en mode binaire.
J'utilise une boucle While mais je n'arrive pas à détecter la fin de
fichier. J'ai bien utilisé un try except IOError mais aucune exception
n'est levée. Quelqu'un aurait-il une idée. Merci.


Un extrait du code:

while not EOF:

offset = f.tell()
#print offset

try:
record = f.read(46)

except IOError:
EOF = -1
print "End of file"
except:
print "Autre erreur"

1 réponse

Avatar
Yermat
Pierrot wrote:
Bonjour,
Je débute en Python. Je souhaite lire un fichier en mode binaire.
J'utilise une boucle While mais je n'arrive pas à détecter la fin de
fichier. J'ai bien utilisé un try except IOError mais aucune exception
n'est levée. Quelqu'un aurait-il une idée. Merci.


Un extrait du code:

while not EOF:

offset = f.tell()
#print offset

try:
record = f.read(46)

except IOError:
EOF = -1
print "End of file"
except:
print "Autre erreur"


Oui il suffit de lire la doc !

read( [size])
Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as a
string object. An empty string is returned when EOF is encountered
immediately. (For certain files, like ttys, it makes sense to continue
reading after an EOF is hit.) Note that this method may call the
underlying C function fread() more than once in an effort to acquire as
close to size bytes as possible. Also note that when in non-blocking
mode, less data than what was requested may be returned, even if no size
parameter was given.

f = open(...,'rb')
recordSize = 46
record = f.read(recordSize)
while len(record) == recordSize:
doSomething(record)
record = f.read(recordSize)
if len(record) != 0:
# le dernier record est tronqué...
f.close()

--
Yermat