Search code examples
pythontextline

Add a particular string (in that case "\\\hline" to prepare a table in latex) at the end of each line of a text file with python


I want to add a particular string (in that case "\\hline" to prepare a table in latex) at the end of each line of a text file

a_file = open("sample.txt", "r")
list_of_lines = a_file.readlines()
for line in range(0, len(list_of_lines)):
  list_of_lines[line] = list_of_lines[line] + r' \\\line'

a_file = open("sample2.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()

Here is sample.txt:

line1
line2
line3

Here is the output:

l1
 \\\linel2
 \\\linel3
 \\\line%

What I want is:

l1 \\\line
l2 \\\line
l3 \\\line

Solution

  • The problem is that you are not removing the linebreak '\n' at the end of your lines.

    The first line actually looks like this: 'line1\n'. When you add your string, then the result is 'line1\n \\\line' which gets displayed with a linebreak in the place of '\n'. So you first need to strip the linebreak, then add your string and a linebreak again.

    Also, I recommend using context managers (with) to open your files , it's much safer than opening and closing the file manually and is considered best practice.

    with open('sample.txt') as file:
        list_of_lines = file.readlines()
        
    for i in range(len(list_of_lines)):
        list_of_lines[i] = list_of_lines[i].rstrip() + r'\\\line' + '\n'
        
    with open('sample2.txt', 'w') as file:
        file.writelines(list_of_lines)