read text file byte by byte

Rhodri James rhodri at wildebst.demon.co.uk
Sun Dec 13 17:56:04 EST 2009


On Sun, 13 Dec 2009 06:44:54 -0000, Steven D'Aprano  
<steve at remove-this-cybersource.com.au> wrote:

> On Sat, 12 Dec 2009 22:15:50 -0800, daved170 wrote:
>
>> 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
>
> That's a statement, not a question.
>
>
>> 2) I need to read each time 1 byte.
>
> f = open(filename, 'r')  # open in text mode
> f.read(1)  # read one byte

The OP hasn't told us what version of Python he's using on what OS.  On  
Windows, text mode will compress the end-of-line sequence into a single  
"\n".  In Python 3.x, f.read(1) will read one character, which may be more  
than one byte depending on the encoding.

If you really want bytes, opening the file in text mode will come back and  
by^Hite you eventually.

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list