.readlines() shouldn't return an array?
<p>I have a problem with <code>.readlines()</code>.
it used to only return the line specified, i.e. if I ran</p>

<pre><code>f1 = open('C:\file.txt','r')
filedata = f1.readlines(2)
f1.close()
print filedata
</code></pre>

<p>it should print the second line of <strong>file.txt.</strong>
However now when I run that same code, it returns the entire contents of the file in an array, with each line in the file as a separate object in the array. I am using the same PC and am running the same version of <code>python (2.7).</code></p>

<p>Does anyone know of a way to fix this?</p>

<p>Don't use <code>readlines</code>; it reads the entire file into memory, <em>then</em> selects the desired line. Instead, just read the first <code>n</code> lines, then break.</p>

<pre><code>n = 2
with open('C:\file.txt','r') as f1:
    for i, filedata in enumerate(f1, 1):
        if i == n:
            break
print filedata.strip()
</code></pre>

<p>The <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code> documentation</a> also provides a recipe for consuming the first <em>n</em> items of an sequence:</p>

<pre><code>def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)
</code></pre>

<p>You might use it like this:</p>

<pre><code>n = 2
with open('C:\file.txt','r') as f1:
    consume(f1, n-1)
    filedata = next(f1)
print filedata.strip()
</code></pre>

python readlines