IOError lors de la mise à jour d'un fichier
Bonjour
Je suis en train de développer une petite bibliothèque de gestion des nombres premiers, et je veux permettre la gestion d'une table pour accélérer les recherches. Les fonctions de recherche dans la table fonctionnent sans problème mais pas celles de mise à jour :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| def SearchForPrimes(self, nmax, verbose = False):
self.fd.seek(0, 2) ##self.fd = open(self.f, "r+b")
n = self.maxn + 1 #plus grand nombre de la table
pos = self.ofs #position du dernier entier écrit
while n < nmax:
if IsPrime(n):
pos = self.fd.tell()
save_int(n, self.fd) #la ligne qui lance l'erreur
self.fd.flush()
self.maxn = n
if verbose: print "Found prime:", n
n += 1
self.fd.seek(0)
self.fd.write(struct.pack("I", pos))
self.fd.flush() |
La fonction save_int:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| def save_int(n, fd):
n = abs(int(n))
s = _int2bin(n)
fd.write(struct.pack("I", len(s))) #c'est ce write qui lance l'erreur
fd.write(s)
def _int2bin(n):
q, r = -1, -1
res = ""
while q != 0:
q, r = divmod(n, 256)
res = chr(r) + res
n = q
return res |
L'erreur:
Citation:
Traceback (most recent call last):
File "E:\Projets\Primes\PrimeOps.py", line 100, in <module>
table.SearchForPrimes(n, True);
File "E:\Projets\Primes\PrimeOps.py", line 44, in SearchForPrimes
save_int(n, self.fd)
File "E:\Projets\Primes\_tools.py", line 7, in save_int
fd.write(struct.pack("I", len(s)))
IOError: [Errno 0] Error
Je ne vois pas ce qui pourrait ne pas fonctionner, vu que si j'essaie:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
| >>> fd = open("tmp.txt", "wb")
>>> fd.write("aaaa")
>>> fd.close()
>>> fd = open("tmp.txt", "r+b")
>>> fd.read(4)
'aaaa'
>>> fd.seek(1)
>>> fd.write("bcd")
>>> fd.flush()
>>> fd.seek(0)
>>> fd.read(4)
'abcd'
>>> fd.close() |
Je n'ai aucune erreur... et le fichier contient bien "abcd"
tu es a la fin du fichier !
il te manque un fd.seek(), afin de repositionner ton 'curseur' et pouvoir écrire de nouveau :)
@++