Printing directly from read() in Python adds an extra newline - python

I've got a Python script that prints out a file to the shell:
print open(lPath).read()
If I pass in the path to a file with the following contents (no brackets, they're just here so newlines are visible):
> One
> Two
>
I get the following output:
> One
> Two
>
>
Where's that extra newline coming from? I'm running the script with bash on an Ubuntu system.

Use
print open(lPath).read(), # notice the comma at the end.
print adds a newline. If you end the print statement with a comma, it'll add a space instead.
You can use
import sys
sys.stdout.write(open(lPath).read())
If you don't need any of the special features of print.
If you switch to Python 3, or use from __future__ import print_function on Python 2.6+, you can use the end argument to stop the print function from adding a newline.
print(open(lPath).read(), end='')

Maybe you should write:
print open(lPath).read(),
(notice trailing comma at the end).
This will prevent print from placing a new-line at the end of its output.

Related

How to overwrite a line with carriage return, using a for-loop in Python?

I'm trying to print out a string with the end=\r to send the cursor back to beginning of the line, and overwrite the printed string using a for loop
This is the code thus far I got :
import time
print("░░░░░░░░░░░░░", end='\r')
for i in ("SECRET"):
print(i ,end='')
time.sleep(0.3)
Ideally, it should slowly overwrite some of the dotted pattern characters with characters from `"SECRET" every 0.3 seconds.
However, when run, the for loop instead iterates and prints characters on a single space, overwriting the characters it prints out itself, instead of advancing to the next available space, overwriting the dot pattern there and typing out the remaining characters in the string it iterates over
Removing the entire print statement associated with the dotted pattern characters allows the loop to function normally, printing out the string it iterates over properly, however, it is needed for the loop to print out the string and overwrite the dotted characters
Essentially, I want to overwrite some of the dotted pattern characters one by one using characters from the string the for loop iterates over, with the help of \r
I am on Ubuntu Studio
Screen output is line-buffered. This means that when you print something followed by a newline it appears on the screen immediately, but if you print something without a newline it might take a while to appear.
This is what's happening to you -- the output inside the for loop is not followed by a newline, so it doesn't appear onscreen immediately.
You can add flush=True to the print call to force the output to appear immediately instead of waiting:
print(i, end='', flush=True)
you can't overwrite characters in python.
you can, though, clear the whole screen by using os.system('cls') on windows or os.system('clear') on linux and unix.
here is the full code:
import time, os
output = '░░░░░░░░░░░░░'
for i in range(7):
print(output)
output = "SECRET"[:i]+output[i:]
time.sleep(0.3)
if os.name == 'nt': #on windows
os.system("cls")
else:
os.system("clear") #not on windows
print(output)
also, this will only work when you are not running from the shell and if you want to see the full output, write time.sleep(1) at the end.

Why print("\5") output a new line in python

What is the difference between print("\n") and print("\5")?
I tried below in a python shell.
Why does print("\5") output a new line:
>>> print("\n")
>>> print("\5")
>>>
But when I tried:
print("\4")
print("\6")
It's printing some binary data
Whenever you use print in python, it puts a newline at the end. The thing you should pay attention to is how many newlines are in the output.
"\5" is just a character (it's the control characters ENQ in ASCII; while it is technically non-printable, my terminal renders it as ♣); printing it outputs whatever your terminal decides to use to render it followed by a newline. print("") will output a newline. print("\n") by contrast will output two newlines.
If your terminal can't/won't render \5 (it is a non-printable character after all), print("\5") will be the same as print("").

Delete last printed character python

I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)

Where does the newline come from in Python?

In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
print adds a newline by default. To avoid this, use a trailing ,:
print "Line 1 is",
print "big"
The , will still yield a space. To avoid the space as well, either concatenate your strings and use a single print statement, or use sys.stdout.write() instead.
From the documentation:
A '\n' character is written at the
end, unless the print statement ends
with a comma. This is the only action
if the statement contains just the
keyword print.
If you need full control of the bytes written to the output, you might want to use sys.stdout
import sys
sys.stdout.write("Line 1 is ")
sys.stdout.write("big!\n")
When not outputing a newline (\n) you will need to explicitly call flush, for your data to not be buffered, like so:
sys.stdout.flush()
this is standard functionality, use print "foo",

Prevent python from printing newline

I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the newline after formatting with the variable. I suspect Python might be taking in the newline as input when I hit return.
How can I make it so that the input does not include any newlines so that I may compare it to other strings/characters? (e.g. something == 'a')
You are correct - a newline is included in inputted. To remove it, you can just call strip("\r\n") to remove the newline from the end:
print("Input is {0}, including the return".format(inputted.strip("\r\n")))
This won't cause any issues if inputted does not have a newline at the end, but will remove any that are there, so you can use this whether inputted is user input or not.
If you don't want any newlines in the text at all, you can use inputted.replace("\r\n", "") to remove all newlines.
Your problem is actually Eclipse. Assuming that you use PyDev, I was able to reproduce the problem. When entering something in the Eclipse console, the problem occurs as described in your question. But when directly executing the very same script with the Python 3.1.1 interpreter, inputted does not include a newline character.
I investigated the Python source code and found out input() uses GNU readline if stdin is interactive (i.e. a TTY or prompt, however you want to call it), but falls back to the .readline() method of the stdin object if necessary. Then, if the result of readline ends with \n, that character is removed. Note: No CR-LF or LF-CR handling here (in the fallback case)!
So I wrote this little script to see what actually happens:
import sys
from io import StringIO
for stdin in [sys.stdin, StringIO("test\r\ntest\r\n")]:
sys.stdin = stdin
print("readline returns this: " + repr(sys.stdin.readline()))
inputted = input("Enter in something: ")
print("inputted: " + repr(inputted))
print("inputted is printed like this: --> {0} <--".format(inputted))
It first executes the code with the normal stdin (console or Eclipse console) and then with a prepared stdin containing the text test\r\ntest\r\n.
Try and run the script in Eclipse - you must enter a string twice. The conclusion: Pressing Enter in the Eclipse console will produce CR-LF ("\r\n"). Printing "\r" in the Eclipse console will jump to the next line.
On the other side, running it in the Windows console will produce the expected output: input() returns a string without a newline at the end because (I guess) GNU readline is used. With the prepared stdin StringIO("test\r\n"), the input() result is "test\r" as in Eclipse (although not printed as newline).
Hope this all makes sense... but what I still don't know is if that is expected behavior of Eclipse.
If you only want to stript the last line endings, you could use rstrip.
inputted.rstrip ("\r\n")
inputted = inputted.strip()
Edit: As noted, this will kill all whitespace at the start and end. A way to get rid of only the trailing newline is:
import re
inputted = re.sub("[\n\r]+$", "", inputted)

Categories

Resources