How to make this code a bit less memory consuming yet simple?
<p>To return a particular line from a txt file for further manipulation, also the file that must be opened by this function is quite big ~ 500 lines so creating a list and then printing a particular line seemed pretty absurd. Can you please suggest me an alternative? The code is as follows :</p>

<pre><code>def returnline(filename, n):  
    ofile = open(filename, 'r')  
    filelist = ofile.readlines()  
    return filelist[n - 1].strip('\n')  
</code></pre>

<p>If your files are not many thousands of lines, I wouldn't worry about optimizing that bit, however, what you can do is simply keep reading the file until you've reached the line you want, and stop reading from there on; that way, when the file is, say, 5000 lines, and you want the 10th line, you'll only have to read 10 lines. Also, you need to close the file after opening and reading from it.</p>

<p>So all in all, something like this:</p>

<pre><code>def line_of_file(fname, linenum):
    # this will ensure the file gets closed
    # once the with block exits
    with open(fname, 'r') as f:

        # skip n - 1 lines
        for _ in xrange(linenum - 1):
            f.readline()

        return f.readline().strip('\n')
</code></pre>

<p>Alternatively, generators (lazy lists, kind of) might provide better performance:</p>

<pre><code>from itertools import islice

def line_of_file(fname, linenum):
    with open(fname, 'r') as f:
        # (lazily) read all lines
        lines = f.xreadlines()
        # skip until the line we want
        lines = islice(lines, linenum - 1, linenum)
        # read the next line (the one we want)
        return next(lines)
</code></pre>

<p>...which can be shortened to:</p>

<pre><code>from itertools import islice

def line_of_file(fname, linenum):
    with open(fname, 'r') as f:
        return next(islice(f.xreadlines(),
                           linenum - 1,
                           linenum))
</code></pre>

<p>(In Python 2.x, <code>islice(xs, n, m)</code> is like <code>xs[n:m]</code> except <code>islice</code> works on generators; see <a href="https://docs.python.org/2/library/itertools.html#itertools.islice" rel="nofollow">https://docs.python.org/2/library/itertools.html#itertools.islice</a>)</p>

python python-2.7 file-handling