read text file byte by byte

sjdevnull at yahoo.com sjdevnull at yahoo.com
Mon Dec 14 01:56:55 EST 2009


On Dec 13, 5:56 pm, "Rhodri James" <rho... at wildebst.demon.co.uk>
wrote:
> On Sun, 13 Dec 2009 06:44:54 -0000, Steven D'Aprano  
>
> <st... 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.

The 3.1 documentation specifies that file.read returns bytes:

file.read([size])
    Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached. The bytes are returned as
a string object. An empty string is returned when EOF is encountered
immediately. (For certain files, like ttys, it makes sense to continue
reading after an EOF is hit.) Note that this method may call the
underlying C function fread() more than once in an effort to acquire
as close to size bytes as possible. Also note that when in non-
blocking mode, less data than was requested may be returned, even if
no size parameter was given.

Does it need fixing?



More information about the Python-list mailing list