Python equivalent of C++ getline()
Asked Answered
D

3

7

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?

Delineator answered 11/6, 2010 at 12:13 Comment(0)
T
3

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(";")
Tube answered 11/6, 2010 at 12:32 Comment(1)
this suits my cause just fine.. :-)Delineator
C
2

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.

Commendam answered 11/6, 2010 at 12:20 Comment(1)
Be careful when using linecache.getline on a file that might have its content modified at some point because, as the module name implies, the read is cached. This can be solved by running linecache.clearcache() before getting the line.Enginery
S
0

You will need to implement such a function yourself. For example:

def getline(stream, delimiter="\n"):
  def _gen():
    while 1:
      line = stream.readline()
      if delimiter in line:
        yield line[0:line.index(delimiter)]
        break
      else:
        yield line
  return "".join(_gen())

import sys
getline(sys.stdin, ".")
Sifuentes answered 11/6, 2010 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.