read text file byte by byte
Dave Angel
davea at ieee.org
Sun Dec 13 02:32:46 EST 2009
daved170 wrote:
> On Dec 13, 2:34 am, Dennis Lee Bieber <wlfr... at ix.netcom.com> wrote:
>
>> On Sat, 12 Dec 2009 10:46:01 +0100, census <cen... at no-email.de>
>> declaimed the following in gmane.comp.python.general:
>>
>>
>>
>>
>>> def scramble (a): return (a + 13) % 256
>>>
>> I'll see your modulo rot 13 and raise with a exclusive or...
>>
>> -=-=-=-
>>
>> import sys
>>
>> def scramble(block, key=on't look"):
>> copies =nt(len(block) / len(key)) + 1
>> keystring =ey * copies
>> return "".join([ chr( ord(block[i])
>> ^ ord(keystring[i]))
>> for i in range(len(block))])
>>
>> def process(fin, fout, key=ne):
>> din =pen(fin, "rb")
>> dout =pen(fout, "wb")
>> while True:
>> block =in.read(1024)
>> if not block: break
>> if key is None:
>> block =cramble(block)
>> else:
>> block =cramble(block, key)
>> dout.write(block)
>> dout.close()
>> din.close()
>>
>> if __name__ ="__main__":
>> fin =ys.argv[1]
>> fout =ys.argv[2]
>> if len(sys.argv) > 3:
>> key =ys.argv[3]
>> else:
>> key =one
>> process(fin, fout, key)
>> --
>> Wulfraed Dennis Lee Bieber KD6MOG
>> wlfr... at ix.netcom.com HTTP://wlfraed.home.netcom.com/
>>
>
>
> Thank you all.
> Dennis I really liked you solution for the issue but I have two
> question about it:
> 1) My origin file is Text file and not binary
> 2) I need to read each time 1 byte. I didn't see that on your example
> code.
> Thanks again All of you
> Dave
>
>
If you really need to see each byte of the file, you need to open it as
binary. You can then decide that the bytes represent text, in some
encoding. If you don't use the "b" flag, the library may change the
newline characters out from under you. You have to decide if that matters.
I may have missed it, but I don't think you ever explained why you
insist on the data being read one byte at a time. Usually, it's more
efficient to read it into a buffer, and process that one byte at a
time. But in any case, you can supply your own count to read().
Instead of using 1024, use 1.
DaveA
More information about the Python-list
mailing list