Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of C++ getline()

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?

like image 904
Arnab Sen Gupta Avatar asked Jun 11 '10 12:06

Arnab Sen Gupta


2 Answers

Do you still want to press enter to create multiple lines? How do you end the input? Or do you want do specify multiple lines on a single line?

If the former, try looping raw_input() until something is written that tells it to stop:

lines = []
while True:
    user_input = raw_input()
    if user_input.strip() == "": # empty line signals stop
        break
    lines.append(user_input)

Or to specify multiple lines on a single line using a delimiter:

lines = raw_input().split(";")
like image 153
Mizipzor Avatar answered Nov 13 '22 08:11

Mizipzor


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.

like image 33
bigbluedragon Avatar answered Nov 13 '22 08:11

bigbluedragon