Reading a line from standard input in Python

Grigor Gevorgyan picture Grigor Gevorgyan · Aug 6, 2011 · Viewed 52.5k times · Source

What (if any) are the differences between the following two methods of reading a line from standard input: raw_input() and sys.stdin.readline() ? And in which cases one of these methods is preferable over the other ?

Answer

Frédéric Hamidi picture Frédéric Hamidi · Aug 6, 2011

raw_input() takes an optional prompt argument. It also strips the trailing newline character from the string it returns, and supports history features if the readline module is loaded.

readline() takes an optional size argument, does not strip the trailing newline character and does not support history whatsoever.

Since they don't do the same thing, they're not really interchangeable. I personally prefer using raw_input() to fetch user input, and readline() to read lines out of a file.