Reputation: 13
I'm trying to add XML tags around a text document. Here is my code
def codeData(filename):
file = open(str(filename), "r")
info = file.readlines()
file.close()
#reopen the file
file2 = open(str(filename), "w")
for line in info:
line = line.replace(line, "<test> " + line + "</test>")
file2.write(line)
file2.close()
Here is my result: https://gyazo.com/c790b6bc6a1af7f42edc1dfe8d5ca2aa
I want the words to be in the middle of the tags. Could someone give me some assistance?
Upvotes: 1
Views: 31
Reputation: 5637
This is caused by the newline
character at the end of each line in your file. A way to remedy this problem is to remove that newline
at the end of each line.
line = line.replace(line, "<test> " + line.rstrip('\n') + "</test>\n")
Upvotes: 1