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.
Dave Jarvis
31.3k43 gold badges186 silver badges327 bronze badges
asked Nov 30, 2011 at 1:34
amedeiros
9493 gold badges15 silver badges24 bronze badges
2 Answers 2
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())
answered Nov 30, 2011 at 1:37
srgerg
19.4k4 gold badges59 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Nov 30, 2011 at 1:36
TJD
11.9k1 gold badge28 silver badges34 bronze badges
Comments
lang-py