Open() and in Python 2.7 behave strangely different

I have a text file with first line of unicode characters and all other lines in ASCII.
I try to read the first line as one variable, and all other lines as another. However, when I use the following code:

# -*- coding: utf-8 -*-
import codecs
import os
filename = '1.txt'
f =, 'r3', encoding='utf-8')
print f
names_f = f.readline().split(' ')
data_f = f.readlines()
print len(names_f)
print len(data_f)
print 'And now for something completely differerent:'
g = open(filename, 'r')
names_g = g.readline().split(' ')
print g
data_g = g.readlines()
print len(names_g)
print len(data_g)

I get the following output:

<open file '1.txt', mode 'rb' at 0x01235230>


And now for something completely differerent:

<open file '1.txt', mode 'r' at 0x017875A0>



If I don’t use readlines(), whole file reads, not only first 7 lines both at and open().

Why does such thing happen?
And why does read file in binary mode, despite the ‘r’ parameter is added?

Upd: This is original file:

Solution #1:

Because you used .readline() first, the file has filled a linebuffer; the subsequent call to .readlines() returns only the buffered lines.

If you call .readlines() again, the rest of the lines are returned:

>>> f =, 'r3', encoding='utf-8')
>>> line = f.readline()
>>> len(f.readlines())
>>> len(f.readlines())

The work-around is to not mix .readline() and .readlines():

f =, 'r3', encoding='utf-8')
data_f = f.readlines()
names_f = data_f.pop(0).split(' ')  # take the first line.

This behaviour is really a bug; the Python devs are aware of it, see issue 8260.

The other option is to use instead of; the io library is what Python 3 uses to implement the built-in open() function and is a lot more robust and versatile than the codecs module.

Respondent: Martijn Pieters

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.