Python read input lines through function call
<p>My code below works perfectly to receive my input data (list.txt) and return lines between 2 and 5 to the screen. </p>

<pre><code>def get_list():

    file = open('list.txt', 'r')
    lines = file.read().splitlines()[2:5]
    print (lines)

get_list()
</code></pre>

<p>However I am required to implement something where I can call the function like:</p>

<pre><code>get_list()[2:5] 
</code></pre>

<p>and this would print between lines 2 and 5 instead. Can anyone suggest a possible way I can do this?  Thanks!</p>

<p>As I mentioned in the question comments, this is <em>not</em> a sensible thing to do, but here's how it can be done. To test this code I created a text file containing the integers 0 to 9, using the GNU coreutils command <code>seq</code>:</p>

<pre><code>seq 0 9 &gt;list.txt
</code></pre>

<p>And here's the Python code:</p>

<pre><code>class AutoPrint(object):
    def __init__(self, data):
        self.data = data

    def __getitem__(self, idx):
        for row in self.data[idx]:
            print(row)

def get_list(fname):
    with open('list.txt') as f:
        data = f.read().splitlines()
    return AutoPrint(data)

get_list('list.txt')[2:5]
</code></pre>

<p><strong>output</strong></p>

<pre><code>2
3
4
</code></pre>

<p>But <em>please</em> don't do crazy stuff like this in real code! My <code>__getitem__</code> method returns <code>None</code>; a proper <code>__getitem__</code> is supposed to return the selected item(s). And it shouldn't have crazy side-effects, like printing stuff. OTOH, I guess while you're developing the code it <em>can</em> be handy for it to print (or log) stuff so that you know that it's doing what you expect it to do. </p>

python file text input