This question already has answers here:
How to read multiple lines of raw input?
(16 answers)
Closed 6 years ago.
I want to write a program that gets multiple line input and work with it line by line. Why isn't there any function like raw_input in Python 3?
input does not allow the user to put lines separated by newline (Enter). It prints back only the first line.
Can it be stored in a variable or even read it to a list?
raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
Python 3
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
Python 2
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n
To get multi-line input from the user you can go like:
no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"
print(lines)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
input(prompt) is basically equivalent to
def input(prompt):
print(prompt, end='', file=sys.stderr, flush=True)
return sys.stdin.readline()
You can read directly from sys.stdin if you like.
lines = sys.stdin.readlines()
lines = [line for line in sys.stdin]
five_lines = list(itertools.islice(sys.stdin, 5))
The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.
Use the input() built-in function to get a input line from the user.
You can read the help here.
You can use the following code to get several line at once (finishing by an empty one):
while input() != '':
do_thing
no_of_lines = 5
lines = ""
for i in xrange(5):
lines+=input()+"\n"
a=raw_input("if u want to continue (Y/n)")
""
if(a=='y'):
continue
else:
break
print lines
Related
Imagine unlimited multiline input with some URL addresses, for example:
How would you get that addresses from the input separately?
Following was close, but actually not helping:
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
source: How to get multiline input from user
And other advices I consider completely useless: https://python.plainenglish.io/taking-multiple-inputs-from-user-in-python-3-6cbe02d03a95
If I understand the problem correctly, this may help:
lines = []
try:
while line := input():
lines.append(line)
except EOFError:
pass
print(lines)
This will handle both interactive and redirected input (stdin)
There is a function you could use:
import sys
sys.stdin.read()
But I'm not sure this is a great idea because it won't know when to stop reading. The traditional input() function will detect a \n symbol via the return key, then end input.
I think looping would be the best way forward.
Like:
urls = ''
while True:
url = input()
if url:
urls += url + '\n'
else:
break
Have a nice day.
I try to output the sum of 1 - 12 lines which contain each two numbers which are seperated by ' '. Because I don't know how many lines will be inputed, I have an endless loop, which will be interupted if the line is empty. But if there is no input anymore, there won't be any empty input and the program is stuck in the input function.
while True:
line = input()
if line:
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
else:
break
So after the last outputed sum I want the program to stop. Maybe it is possible with a time limit?
It looks like the automated input is coming in via sys.stdin. In that case you can just read from the standard input stream directly. Try this:
def main():
import sys
lines = sys.stdin.read().splitlines()
for line in lines:
print(sum(map(int, line.split())))
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
With an input of "1 2\n3 4" to the sys.stdin stream, this script prints 3 and 7.
For the case without timeout, and the case allowing you to capture the content (which is usually handy).
The following code has been tested in HACKERRANK. I am sure HackerEarth is the same.
contents = []
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
contents.append(line)
if you don't care about the input.
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
I have been trying to create a program that lets users name, write and save documents, here is what I have come up with so far:
doc_name = str(input("Document Name: "))
end = ""
for line in iter(input, end):
document = "\n".join(iter(input, end))
pass
try:
savefile = open("/home/" +doc_name+ ".txt", "w")
savefile.write(x)
savefile.close()
print("Document - " +doc_name+ "\nSuccessfully saved.\n\n")
except:
print("An error occurred.\nUnable to save document.\n\n")
The 'for loop' I have used was from the following page:
Raw input across multiple lines in Python but I am unsure how to use the input from this loop, so I am able to save it to a textfile.
I need the input in this line of code in the place of x:
savefile.write(x)
I am using Python 3.2.3 for this program (if that helps?).
I would like to know how the user input entered during the for loop can be stored in a varible and then used at some other point in the program.
Thanks.
doc_name = input("Document Name: ") # don't need to cast to str
end = ""
result = [] # I recommend initializing a list for the lines
for line in iter(input, end): # you only need this single input call
result.append(line) # add each line to the list
try:
# using "with" in this manner is guaranteed to close the file at the end
with open("/home/" +doc_name+ ".txt", "w") as savefile:
for line in result: # go through the list of lines
# write each one, ending with a newline character
savefile.write(line + '\n')
except IOError:
print("An error occurred.\nUnable to save document.\n\n")
else: # print this if save succeeded, but it's not something we want to "try"
print("Document - " +doc_name+ "\nSuccessfully saved.\n\n")
You only need to use pass when Python expects statements (such as in an indented block) but you have no statements for it to execute - it's basically a placeholder. The common use is when you want to define your program's functions (e.g., def myfunction(a, b):) but you don't have the actual content for them yet.
My current code reads user input until line-break.
But I am trying to change that to a format, where the user can write input until strg+d to end his input.
I currently do it like this:
input = raw_input ("Input: ")
But how can I change that to an EOF-Ready version?
In Python 3 you can iterate over the lines of standard input, the loop will stop when EOF is reached:
from sys import stdin
for line in stdin:
print(line, end='')
line includes the trailing \n character
Run this example online: https://ideone.com/rUXCIe
This might be what most people are looking for, however if you want to just read the whole input until EOF into a single variable (like OP), then you might want to look at this other answer.
Use file.read:
input_str = sys.stdin.read()
According to the documentation:
file.read([size])
Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached.
>>> import sys
>>> isinstance(sys.stdin, file)
True
BTW, dont' use input as a variable name. It shadows builtin function input.
You could also do the following:
acc = []
out = ''
while True:
try:
acc.append(raw_input('> ')) # Or whatever prompt you prefer to use.
except EOFError:
out = '\n'.join(acc)
break
With sys.stdin.readline() you could write like this:
import sys
while True:
input_ = sys.stdin.readline()
if input_ == '':
break
print type(input_)
sys.stdout.write(input_)
Remember, whatever your input is, it is a string.
For raw_input or input version, write like this:
while True:
try:
input_ = input("Enter:\t")
#or
_input = raw_input("Enter:\t")
except EOFError:
break
print type(input_)
print type(_input)
print input_
print _input
This question already has answers here:
NameError when using input() [duplicate]
(2 answers)
Closed 9 years ago.
I've created a few test programs to show what I mean
import os
r = open('in.txt', 'r')
for line in r.readlines():
print line
Above program prints every line in 'in.txt' which is what I want with the others
for line in raw_input():
print line
I input "asdf" and it gives me (it also does not let me input multiple lines)
a
s
d
f
Lastly,
for line in str(input()):
print line
I input "asdf" and it gives me (does not let me input multiple lines)
Traceback (most recent call last):
File "C:/Python27/test.py", line 1, in <module>
for line in str(input()):
File "<string>", line 1, in <module>
NameError: name 'asdf' is not defined
Can someone please tell me what is going on?
What is the difference between these 3 input methods other than reading files and standard input?
raw_input() takes one line as input from the user and gives a string, and when you loop through with for ... in you're looping through the characters.
input() takes the input and executes it as Python code; you should rarely if ever use it.
(In Python 3, input does the same thing as Python 2's raw_input, and there is not a function like Python 2's input.)
If you want multiline input, try:
lines = []
while True:
line = raw_input()
if line == '': break
lines.append(line)
for line in lines:
# do stuff
pass
Input a blank line to signal end of input.
Pursuant to your secondary question in Doorknob of Snow's answer, here's sample code but be aware, THIS IS NOT GOOD PRACTICE. For a quick and dirty hack, it works alright.
def multiline_input(prompt):
"""Prompts the user for raw_input() until an empty string is entered,
then returns the results, joined as a string by the newline character"""
tmp = "string_goes_here" #editor's note: this just inits the variable
tmp_list = list()
while tmp:
tmp_list.append(tmp)
tmp = raw_input(prompt)
input_string = '\n'.join(tmp_list[1:])
return input_string
for line in multiline_input(">> ").splitlines():
print(line)