Overwrite just one line? Am I a n00b or is this impossible? Both? :D

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Apr 6 17:11:57 EDT 2005


In <1112821286.411004.225400 at f14g2000cwb.googlegroups.com>, Matt at revera
wrote:

> I'd like to overwrite just one line of a binary file, based on a
> position set by seek().  Is there no way to do this? As far as I can
> tell I need to read the whole file, change the line, and write it all
> back out.  Not exactly easy on the memory, but I see no other solution.
> 
> so far:
> 
> 	patchme.seek(offset)
> 	patchme.write(a2b_hex(edit)) # the data is in hex first
> 	patchme.close
> 	print "Patching complete"
> 
> This writes the data at the given offset, but _everything_ before it is
> filled with 0's.

Are you sure that you haven't opened the file with the wrong mode? ::

  In [69]: f = open('test.dat', 'w')

  In [70]: f.seek(1000)

  In [71]: f.write('hello')

  In [72]: f.close()

  In [73]: f = open('test.dat')

  In [74]: a = f.read()

  In [75]: f.close()

  In [76]: a
  Out[76]:
  '\x00\x00\x00\x00\x00\x00\x00\00<...>hello

If you want to open an existing file without overwriting it you have to
use mode "w+" or "a".

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list