sourcenouveau
sourcenouveau

Reputation: 30504

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

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.

Upvotes: 1

Views: 240

Answers (2)

agf
agf

Reputation: 176740

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='')

Upvotes: 8

julx
julx

Reputation: 9091

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.

Upvotes: 1

Related Questions