0

I want to remove the \n that comes at the end of every line of a text file as i need to put each line as a separate list item in a list.

with open("PythonTestFile.txt", "rt") as openfile:

    for line in openfile:
        new_list = []

        new_list.append(line)

        print(new_list)

This is what i get

['1) This is just an empty file.\n']

['2) This is the second line.\n']

['3) Third one.\n']

['4) Fourth one.\n']

['5) Fifth one.\n']

This is what I want

['1) This is just an empty file.']

['2) This is the second line.']

['3) Third one.']

['4) Fourth one.']

['5) Fifth one.']
newkid
  • 1,368
  • 1
  • 11
  • 27
Mohamed Motaz
  • 391
  • 1
  • 4
  • 13

2 Answers2

2

Try using string.strip()

with open("PythonTestFile.txt", "rt") as openfile:
    new_list = []
    for line in openfile:
        new_list.append(line.rstrip('\n'))

    print(new_list)
cmccandless
  • 140
  • 10
  • 1
    Using `.strip` without argument removes whitespace characters, not only newline, so for example if line end is space it would be discarded too. It is better to use `.strip('\n')` which would discard only newline character. – Daweo Feb 05 '19 at 18:44
  • @Daweo good point; editing my answer to use `rstrip('\n')` – cmccandless Feb 05 '19 at 18:49
  • 1
    a@Daweo and @cmac thank u soo much guys – Mohamed Motaz Feb 06 '19 at 06:45
1
line = line.rstrip('\n')

This will take the newline character at the end of the line off.

underasail
  • 63
  • 1
  • 8