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)
Related
I want to read input from STDIN like this:
1,0
0,0
1,0
1,0
and so on until the new line is empty(\n). This signifies the end of the input.
I did this
while (raw_input()!='\n'):
actual,predicted=raw_input().split(',')
Gave me this error when I entered "enter" in last input
0,0
0,1
1,0
1,1
1,1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-3ec5186ad531> in <module>()
5
6 while (raw_input()!='\n'):
----> 7 actual,predicted=raw_input().split(',')
8 if (actual==1 and predicted==1):
9 t_p+=50
ValueError: need more than 1 value to unpack
What's wrong?
OK, there are two problems here: raw_input strips the trailing newline, so a blank input becomes an empty string, not a newline.
The larger issue is that raw_input consumes the input, so your code won't work properly - it will only process every second line. The while loop calls raw_input (which uses up some input and discards it), then the body of the loop calls it again and assigns it to actual and predicted.
The python idiom for this task is a while True: loop containing a break:
while True:
line = raw_input()
if not line:
break
actual, predicted = line.split(",")
print("a, p", actual, predicted)
print("done!")
raw_input() strips the trailing newline, so you want to compare to ''.
But you're also reading two lines at a time in your loop, where I think you want something more like:
data = raw_input()
while (data != ''):
actual,predicted=data.split(',')
data = raw_input()
raw_input is really used when you're writing a user-interactive program. It sounds like your program is a more typical UNIX program which processes file input.
sys.stdin is an open file. Because of this, you can use my favorite feature of Python which is iterating over each line in a file. Ditch the raw_input altogether and just treat your data as if it were a file:
for line in sys.stdin:
line = line.strip()
parts = line.split(',')
This question already has answers here:
f.read coming up empty
(5 answers)
Closed 7 years ago.
I have this function which simply opens a text files and read lines:
def select_word(model):
lines = model.read().splitlines()
selectedline = random.choice(lines)
return [selectedline.split(":")[0],selectedline.split(":")[1]]
when I call this function for just one, there is no problem. But when I call it more than once:
print select_word(a)
print select_word(a)
print select_word(a)
print select_word(a)
print select_word(a)
I got this error:
Traceback (most recent call last):
File "wordselect.py", line 58, in <module>
print select_word("noun")
File "wordselect.py", line 19, in select_word
selectedline = random.choice(lines)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
IndexError: list index out of range
What is the problem with that function?
import random
def select_word(model):
with open(model, 'r') as f:
lines = f.read().splitlines()
selectedline = random.choice(lines)
return [selectedline.split(":")[0],selectedline.split(":")[1]]
result = select_word('example.txt')
print result
I did this and didnt get a problem.
just make sure that in the file you are opening you have something like.
Line: 1
Line: 2
random.choice raises IndexError if you pass it an empty sequence. This happens when you call .read() on a file object the second time (you can only do it once, subsequent calls will return an empty string).
To fix the function, you could read the file once then pass the lines to the function, e.g.:
lines = list(model)
def select_word(lines):
selectedline = random.choice(lines)
return selectedline.split(":", 1)
File handles operate like generators. Once you have read a file, you have reached the end of stream.
model.seek(0) # bring cursor to start of file after reading, at 2nd line of the function
This question already has answers here:
How can I iterate over overlapping (current, next) pairs of values from a list?
(12 answers)
Closed last month.
I am trying to edit a text file using fileinput.input(filename, inplace=1)
The text file has say 5 lines:
line 0
line 1
line 2
line 3
line 4
I wish to change data of line 1 based on info in line 2.
So I use a for loop
infile = fileinput.input(filename, inplace=1)
for line in infile:
if(line2Data):
#do something on line1
print line,
else:
line1=next(infile)
line2=next(infile)
#do something with line2
Now my problem is after the 1st iteration the line is set to line2 so in 2nd iteration the line is set to line3. I want line to be set to line1 in 2nd iteration. I have tried line = line but it doesn't work.
Can you please let me know how I am reset the iteration index on line which gets changed due to next
PS: This is a simple example of a huge file and function I am working on.
As far as I know (and that is not much) there is no way in resetting an iterator. This SO question is maybe useful. Since you say the file is huge, what I can think of is to process only part of the data. Following nosklos answer in this SO question, I would try something like this (but that is really just a first guess):
while True:
for line in open('really_big_file.dat')
process_data(line)
if some_condition==True:
break
Ok, your answer that you might want to start from the previous index is not captured with this attempt.
There is no way to reset the iterator, but there is nothing stopping your from doing some of your processing before you start your loop:
infile = fileinput.input("foo.txt")
first_lines = [next(infile) for x in range(3)]
first_lines[1] = first_lines[1].strip() + " this is line2 > " + first_lines[2]
print "\n".join(first_lines)
for line in infile:
print line
This uses next() to read the first 3 lines into a list. It then updates line1 based on line2 and prints all of them. It then continues to print the rest of the file using a normal loop.
For your sample, the output would be:
line 0
line 1 this is line2 > line 2
line 2
line 3
line 4
Note, if your are trying to modify the first lines of the file itself, rather than just display it, you would need to write the whole file to a new file. Writing to a file does not work like in a Word processor where all the lines move down when a line or character is added. It works as if you were in overwrite mode.
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
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 8 years ago.
I am trying to process a txt file I created of songs and genres, but don't know how to tell python what to look for. The txt file is formatted like so:
7/28/2012
1.1. Lovin’ You Is Fun—Country
[...]
1.100. Call Me Maybe—Teen pop, dance-pop
[]2. 7/27/2013
2.1. Crown—Hip hop
(brackets not in actual file)
I've tried writing code to find certain words in lines, but the code finds every line of the file as containing whatever string I pass it (even when that's obviously not the case). Here's the code:
try:
infilehandle = open(afile, "r")
alllines = infilehandle.read().splitlines(False)
infilehandle.close()
except:
alllines=None
print "Unable to read file {0}".format(afile)
for aline in alllines:
if aline.find("Country"):
country_count += 1
if aline=="1. 7/28/2012" or "2. 7/27/2013" or "3. 4/27/2013" or "3. 4/27/2013":
continue
else:
continue
If the code worked the way I wanted it to, it would categorize each line by the first number on the line, then search for certain strings and add to a count for those strings. Is this possible to do?
You should write:
if aline.find("Country") != -1:
or even better would be
if "Country" in aline:
Also, your second if should read:
if aline=="foo" or aline=="bar" or aline=="zom":
Find doesn't return a boolean. It returns an int. In particular, it returns -1 if it doesn't find the string.
And as jonrsharpe mentions, you are using or incorrectly, also.
try:
infilehandle = open(afile, "r")
alllines = infilehandle.read().splitlines(False)
infilehandle.close()
except:
alllines=None
print "Unable to read file {0}".format(afile)
exit(1)
for aline in alllines:
if aline.find("Country") != -1:
country_count += 1
if aline=="1. 7/28/2012" or
aline=="2. 7/27/2013" or
aline=="3. 4/27/2013" or
aline=="3. 4/27/2013":
pass # I have no idea what you're trying to do here