0

I am accessing a text file of the form

Name1
Name2
Name3
...

with the following code:

names = []
with open('./[path]/text_doc.txt', mode='r') as file:
    names = file.readlines()

for name in names:
    name = name.strip('\n')

print(names)

This produces the following list, and I have no idea why:

['Name1\n', 'Name2\n', 'Name3\n', ...]

I don't understand what in my code is failing to remove these trailing newline characters – names is identical before and after the for loop, which doesn't make any sense to me as what is in the for loop should explicitly remove the newline characters from each entry in the list.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
moistnar
  • 75
  • 4
  • 1
    Or more specifically, https://stackoverflow.com/questions/15233340/getting-rid-of-n-when-using-readlines – mkrieger1 Jun 22 '22 at 21:22
  • 1
    Because you never modified your list, `names`. You simply created *new strings* and assigned them to the local variable `name` – juanpa.arrivillaga Jun 22 '22 at 21:22
  • "which doesn't make any sense to me as what is in the for loop should explicitly remove the newline characters from each entry in the list." No, it doesn't modify any of the objects in the list, nor does it modify the list itself. – juanpa.arrivillaga Jun 22 '22 at 21:24
  • Consider, `s = "hello"; s.strip("o"); print(s)` – juanpa.arrivillaga Jun 22 '22 at 21:24
  • Your loop does not modify `names`, it only stores each strip result in `name`, and overwrites it each time. That’s why `names` does not change before and after the loop. – mhopeng Jun 22 '22 at 21:26
  • `names = [name.strip('\n') for name in names]` would work, though, basically by making a new version of names. – Joffan Jun 22 '22 at 21:29

0 Answers0