I am a total newbie trying to teach myself Python for personal growth and development. So please go easy on me. (If ever have any biology questions, I'll be happy to return the favor!)
I am trying to write a program in PyCharm CE on MacOSX (10.14.2 Mojave) to do the following:
1) let the user enter a chunk of text with multiple lines at once by copying/pasting from a source. For instance:
Mary and Beth
went to
the park.
2) Join all the lines into one, replacing the \n for spaces, as follows:
Mary and Beth went to the park.
I've been doing a lot of reading around, and I've found that a preferred way to have users enter a multi-line piece of text at once is using sys.stdin.readlines(), making sure that the user calls an End Of File with Control-D. So far I've come up with the following
import sys
print('''What is the text that you would like to enter?
(press command-d at the end)\n''')
orig_text = sys.stdin.readlines()
one_string = "".join(orig_text)
one_string = one_string.replace('\n','')
print(one_string)
So far, so good - one_string prints "Mary and Beth went to the park."
The problem is further down the code, when I use a regular input() function...
search_word = input('Which word would you like to replace?')
print(search_word)
I get the following error message: EOFError: EOF when reading a line
I've seen posts from others with a similar problem, and some answers suggest that I try...
sys.stdin.close()
sys.stdin = open('/dev/tty')
search_word = input('Which word would you like to replace?')
print(search_word)
I tried that, but now I get the following error: OSError: [Errno 6] Device not configured: '/dev/tty'. I also tried sys.stdin.flush(), to no avail.
At this point, I gave up and decided to ask the professionals: a) Are there better approaches to having a user copy and paste multi-line text into the program; b) If my approach so far is OK, how can I get rid of the OSError without breaking my computer?
Thanks a ton in advance! Mariano
sys.stdin.readline() isn't a good solution.
You could use the fileinput
module:
import fileinput
for line in fileinput.input():
... code ...
fileinput
will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.
Your code could be substituted by
one_string = "".join(map(str.rstrip, fileinput.input()))
rstrip removes trailing line feeds and spaces.