Python equivalent of C++ getline()

Arnab Sen Gupta picture Arnab Sen Gupta · Jun 11, 2010 · Viewed 18.1k times · Source

In C++ we can enter multiple lines by giving our own choice of delimiting character in the getline() function.. however I am not able to do the same in Python!! it has only raw_input() and sys.stdin.readline() methods that read till I press enter. Is there any way to customize this so that I can specify my own delimiter?

Answer

bigbluedragon picture bigbluedragon · Jun 11, 2010

You can try modify this method a bit to use it and use it in your program.

First, import the linecache module:

import linecache

The linecache module allows you to access any line from any file. Of its three methods, the one you are likely to use the most is getline. The syntax for getline is as follows:

linecache.getline('filename', line_number)

If you have a file called 'myfile.txt' and would like to read line 138 from it, getline allows you to do so with ease.

retrieved_line = linecache.getline('myfile.txt', 138)

Then you can simply print retrieved_line or otherwise manipulate the data of line 138 without doing surgery on the file itself.