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.
Related
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 to read unknown number of lines from stdin in python3. Is there a way to do this without any modules? One more question: How to denote end of input for multiple lines in python3?
Try something like this
a_lst = [] # Start with empty list
while True:
a_str = input('Enter item (empty str to exit): ')
if not a_str: # Exit on empty string.
break
a_lst.append(a_str)
print(a_lst)
We can use try and except in the following way
while True:
try:
n = int(input())
# Perform your operations
except EOFError:
# You can denote the end of input here using a print statement
break
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
I need to search for something in a tab delimited text file. The user is supposed to input both the file and the thing that needs searching for. The programme is then supposed to return the whole line that the user inputted word is in. I have got two models so far because I've been coming at this problem from different angles. The first programme goes as follows:
import csv
searchfile = raw_input ('Which file do you want to search? ')
try:
input_file = open (searchfile, 'rU')
except:
print "Invalid file. Please enter a correct file"
csv_file_object = csv.reader(open(searchfile, 'rb'))
header = csv_file_object.next()
data=[]
for row in csv_file_object:
data.append(row)
searchA = raw_input ('which author?')
author_search = data[0::,0] == searchA
if author_search in searchfile:
print author_search
The problem with the first programme is that this error pops up:
TypeError: list indices must be integers, not tuple
I therefore attempted this method:
import csv
searchfile = raw_input ('Which file do you want to search? ')
try:
input_file = open (searchfile, 'rU')
except:
print "Invalid file. Please enter a correct file"
with open(searchfile) as f:
reader = csv.reader(f, delimiter="\t")
d = list(reader)
searchtype = raw_input ('Search on author or journal/conference or [Q = quit]')
if searchtype == 'author':
searchdataA = raw_input ("Input author name")
if searchdataA in input_file:
print line
elif searchtype == 'journal' or 'conference' or 'journal/conference':
searchdataJ = raw_input ("input journal/conference name")
if searchdataJ in d:
print line
elif searchtype == 'Q':
print "Program left"
else:
print "please choose either author or journal/conference"
This is unable to get beyond inputting the search parameters.
Any help on where to go with either programme would be much appreciated, or if I'm completely on the wrong track then links to useful material would be great.
I think you're making this a bit more complicated than it needs to be. Since you want to print the whole line that the target word appeared on, you don't really need the CSV module. You're not doing any of the sophisticated parsing it is capable of.
searchfile = raw_input ('Which file do you want to search? ')
searchA = raw_input ('which author?')
with open(searchfile) as infile:
for line in infile:
if searchA in line:
print(' '.join(line.split()))
break # remove this if you want to print all matches instead of
# just the first one
Notice that in the when printing the line, I first split the line (which splits on whitespace by default), then rejoin the fields with two spaces between them. I think doing something like this would be a good way to go for you since you're printing tab-separated fields on the console. Reducing that extra space will make your prints a bit easier to read, but using two spaces still makes it easy to distinguish the columns from each other.
You can generalize it by prompting your user for any search term, instead of specifying "author". This may be the way to go, since your second code snippet suggests that you may want to search for other fields, like "journal" or "conference":
target_term = raw_input("Which term or phrase would you like to find?")
Since this method searches in and prints the entire line, there's no need to deal with the separate columns and different kinds of search terms. It just looks at the whole row at once and prints a matching line.
Since you are not really using a different search method, depending on if you are searching for author, journal, conference or journal/conference. So you could actually do a full text search on the line. Therefore it is wise to collect all data you need from user BEFORE processing file, so you can output just the matching lines. If user passes a rather large CSV file, then your way would take up far too much memory.
with open(searchfile, 'r') as f:
for line in f:
if line.find(searchA) > -1:
print line
This way you are looping through the file as fast as possible and prints out all matching lines.
The .find() function returns the index to where in the string he found the match and otherwise -1 if the string was not found. So from the value you could "estimate" on where the match was made, but if you really want to differentiate between author, journal, etc. then you will have to split the line. In my sample i will assume the author field to be the sixth field in the CSV line:
with open(searchfile, 'r') as f:
for line in f:
fields = line.split("\t")
if len(fields) > 5: # check length of fields array
if fields[5].find(searchA) > -1: # search straight in author field
print line # return full line
why not simply
fname = raw_input("Enter Filename")
author = raw_input("Enter Author Name:")
if author in open(fname,"rb").read():
print "match found"
if you want to see the lines you could do
print re.findall(".*%s.*"%(author),open(fname,"rb").read())
as people point out it is better form to do
with open(fname,"rb") as f:
data = print re.findall(".*%s.*"%(author),f.read())
although in CPython it will be garbage collected immediatly so its not really a problem....
The first thing that came to my mind is simply:
def check_file(file_name, author_name):
with open(file_name) as f:
content = f.readlines()
for line in content:
if author_name in line:
print "Found: ", line
Hope it can be useful.
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