amedeiros
amedeiros

Reputation: 949

Python string issue

This is to take text from a file and combine with a string to print to a new file for a combined result

file = open('/home/user/facts', 'r')
result = open('/home/user/result.txt', 'a')
i = 1
for line in file:
    print >>result, "fact_text[%d] = \"%s\";"% (i, line)
    i += 1

For some reason the "; is showing up on a separate line, and I do not know why. Thanks in advance.

Upvotes: 2

Views: 88

Answers (2)

srgerg
srgerg

Reputation: 19339

When reading lines from a file using for line in file the resulting string contains a newline character. You can strip it off using line.strip(). So your print statement becomes:

print >>result, "fact_text[%d] = \"%s\";" % (i, line.strip())

Upvotes: 6

TJD
TJD

Reputation: 11896

Because line contains a newline character at the end. You could trim it by doing line[:-1] or -2, depending on if you have DOS or Unix line endings

Upvotes: 1

Related Questions