pythonreadfilewritefile

Add a char to the beginning and end of each line in a file


I have a text file that each line contains exactly one word. I want update the file by attaching a char to the beginning and end of each word in each line. Here is my code in Python:

appendText='_'
names=open("name.txt",'r')
updatedNames=open("name2.txt",'a')
for name in names:
  updatedNames.write(appendText+name+appendText)
updatedNames.close()

But the problem is this code add the _ to the end of line after the \n char. In other words, the output looks like this:

_Name
_

_Name followed by an enter and then in the next line there another _. I want to both _ to be in the same line:

_Name_

Solution

  • You want to remove the newline and then add it back:

    appendText='_'
    names=open("name.txt",'r')
    updatedNames=open("name2.txt",'a')
    for name in names:
      # Python3.5 or earlier:
      # updatedNames.write(appendText + name.rstrip() + appendText + '\n')
      updatedNames.write(f'{appendText}{name.rstrip()}{appendText}\n')
    updatedNames.close()