Reputation: 63
I am trying to remove the \n for every line from the external file then I split the line into 2 lists. However the replacing function is not replacing anything while the code is running without errors.
infile = open('Kaartnummers.txt', 'r')
field1 = []
field2 = []
for items in infile:
items.replace('\n', '')
fields = items.split(", ")
field1.append(fields[0])
field2.append(fields[1])
print(field1, field2)
infile.close()
The external file has the following contents:
325255, Jan Jansen
334343, Erik Materus
235434, Ali Ahson
645345, Eva Versteeg
534545, Jan de Wilde
345355, Henk de Vries
Upvotes: 2
Views: 44
Reputation: 104802
Strings in Python are immutable, so the replace
method cannot work in place. It return
s a new string, rather than changing the existing one. Try:
items = items.replace('\n', '') # save the return value from the replace call
Or perhaps you should use a method more specific to what you're trying to do (remove specific characters from the end of a string):
items = items.rstrip('\n') # or just .strip() if you don't mind removing other whitespace
Upvotes: 4