anzenketh
anzenketh

Reputation: 25

When reading from line returns newline - Python

I am trying to write a python script to generate some code by reading from a file. However it does not work as expected.

Code:

with open('continent.txt') as fp:
    for line in fp:
        print "text ", line ," here"

Results

$ python ContinentCode.py

text  North America
here
text  South America
here
text  Central America

Desired

text  North America here
text  South America here
text  Central America here

Upvotes: 0

Views: 94

Answers (3)

Winny
Winny

Reputation: 1288

Call the .strip() method on line.

with open('continent.txt') as fp:
    for line in fp:
        print "text ", line.strip('\r\n') ," here"

Note the argument to strip specifies what characters to remove. By default .strip() removes spaces and tabs as well... not sure if this is what you want.

Upvotes: 2

Cthulhufish
Cthulhufish

Reputation: 21

Your question seems equivalent to one asked here.

Summarizing the above thread, you can use print "text ", line.rstrip("\n"), " here". line.rstrip("\n") will return remove any "\n" contained in the string line.

Or you could use for line in fp.splitlines(). .splitlines() returns a list of the lines WITHOUT newline characters. Personally, I'm a fan of splitlines. If you want, you can do something like lines = fp.splitlines() for line in lines: [code goes here]

Upvotes: 0

Izaaz Yunus
Izaaz Yunus

Reputation: 2828

Try:

print "text ", line.strip() ," here"

More info about strip here

Upvotes: 0

Related Questions