read text file byte by byte

census census at no-email.de
Sat Dec 12 04:46:01 EST 2009


daved170 wrote:

> Hello everybody,
> I need to read a text file byte after byte.
> Eache byte is sent to a function that scramble it
> and I need to write the result to binary file.
>
> I've got some questions -
> 1) How do I read the file byte by byte
> 2) Should I use streams? If so and I get my entire scrambled text in
> stream can I just write it to the binary file?
>
> Thanks
> Dave

OK, now here a complete code to read a file byte by byte, scramble each
byte (with a really complex algorithm in my example) and write the
output to another file.

def scramble (a): return (a + 13) % 256

infile = open ("binaryfile1", "r")
outfile = open ("binaryfile2", "w")

bytearray = map (ord, infile.read () )
scrambled = map (scramble, bytearray)
map (lambda x : outfile.write (chr (x) ), scrambled)

infile.close ()
outfile.flush ()
outfile.close ()



More information about the Python-list mailing list