File.read () returns different lengths in 2.7 and 3.3

I have a binary file,

file = open(fname,"Ub")
len(file.read())

In Python 3.3, 1279200 is returned, which is correct. In Python 2.7, 1279106 is returned.

What is this going on? What are the possible reasons?

In 2.7, how to get 1279200 bytes?

+3
source share
3 answers

In short, Uthey bdonโ€™t go together.

Python 3 PEP-3116 -. open() , , b Buffered*, TextIOWrapper. , b , .

, open() , . mode U , newline.

, U . , , , .

Python 2 -. io.open(), , Python 3. open(), C file ( : (), , get_line()), . , .

, : . Python 3 , - . b , U, . Python 2 , b, U .


:

$ printf '1\n2\r\n3\n\r4\r5' > f
$ ipython3.3
In [1]: open('f', 'Ub').read()
Out[1]: b'1\n2\r\n3\n\r4\r5'

$ ipython2.7
In [1]: import io

In [2]: io.open('f', 'Ub').read()
Out[2]: '1\n2\r\n3\n\r4\r5'

In [3]: open('f', 'Ub').read()
Out[3]: '1\n2\n3\n\n4\n5'
+1

python documation:

"U" , : Unix '\n', Macintosh '\ r' Windows '\ r\n'. "\n" Python . Python , 'U' - , . , open , newlines, None ( ), '\n', '\ r', '\ r\n' , .

"rb" / "wb", !

0

Python 3 'U' :

"U"  Python. Python 3. newline   .

'b' , len(file.read()) (os.path.getsize(filename)).

Python 2 'U' 'b' . 'b' f_binary ( , ) fopen() ( Unix). 'U' (\r, \r\n \n). , \r\n.

0

All Articles