I am trying to remove ‘\n’ from the end of each element in a list imported from a .txt file
Here is the file I am importing:
NameOfFriends.txt
Joeseph
Mary
Alex
Here is the code I am running
a = open('NameOfFriends.txt', 'r').readlines()
print(a)
newList = str(a)
print(type(newList[0]))
for task in newList:
newList = [task.replace('\n', '') for task in newList]
print(newList)
Here is the output:
['Joeseph\n', 'Mary\n', 'Alex']
<class 'str'>
['[', "'", 'J', 'o', 'e', 's', 'e', 'p', 'h', '\\', 'n', "'", ',', ' ', "'", 'M', 'a', 'r', 'y', '\\', 'n', "'", ',', ' ', "'", 'A', 'l', 'e', 'x', "'", ']']
Here is the desired output when variable newList is printed:
['Joeseph', 'Mary', 'Alex']
>Solution :
with open('NameOfFriends.txt') as file:
names = []
for name in file.readlines():
names.append(name.strip("\n"))
print(names)