How can I change one character in a file without writing the whole file again?
How do I change one character in a file? Any nix-compliant programming language solution is welcome.
I wrote .pgm file and put the magic number to 'P2'. The correct one is 'P5'. Now I have 100000+ files to fix. Alternatively: how do I read my new file with pylab.imread()?
FYI: pgm is an ascii image file format http://netpbm.sourceforge.net/doc/pgm.html. pylab and PIL require magic number to be P5
br, Juha
edit: Thank开发者_运维问答 you for all solutions. dd-method is the only that works. For curiosity, why the c and python do not?
Talking about solutions not involving Python, one would be something like:
echo -n "P5" | dd of=yourfile.pgm conv=notrunc
That will cause dd to write "P5" at the beginning of the file, without truncating it
In C:
FILE* f = fopen("file.txt", "r+b");
fputs("P5", f);
fclose(f);
It'll be the same procedure (open-as-binary/write/close) in just about any language.
Most importantly: First, backup everything.
EDIT: I removed the fseek because the magic string is at the beginning of the file, which is where fopen(..., "r+b")
positions the file pointer.
In python you could memory map the file using the mmap module.
f = open("yourfile.pgm", "rb+")
map = mmap.mmap(f.fileno(), 0)
map[1] = "5"
map.close()
If you know where it is you can read the first x bytes then edit the bytes, then write back.
Well, you will have to save the files after you modify them of course, but I don't see why you'd think you have to rewrite every single byte.
精彩评论