0

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
anzenketh
  • 25
  • 3

3 Answers3

2

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.

Winny
  • 1,189
  • 1
  • 16
  • 29
0

Try:

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

More info about strip here

Izaaz Yunus
  • 2,828
  • 1
  • 19
  • 28
0

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]

Community
  • 1
  • 1