0

I am self studying Python and give myself random tasks to work towards and I am trying to remove the \n from the end of each element in a list that I have created from a text file?

I have seen: How to remove \n from a list element?

However applying this doesn't seem to be working for me and I am not quite sure why? Is anyone able to advise how to strip \n from the end of each element?

word =[]
finalList =[]

#Problem area
dictionary = open ('FILELOCATION\dictionary.txt', 'r')
for line in dictionary.readlines():
    word.append([line])
    for i in line.split():
        finalList[-1].append(i)

#Looping over the list
n = 0
while n < 25:
    print (finalList[n])
    n += 1
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Nataku62
  • 33
  • 1
  • 8
  • Why are you printing `word`s, if you store the result in `finalList`? – thefourtheye Jan 17 '16 at 06:19
  • I am printing them to check that they are in fact stored, I want to draw from them to open a pdf document that is encrypted - task from a book that I am reading (Automate the boring stuff). I can provide that code on here if you need it, but it is a way off from being correct. Just realised what you mean't that was supposed ot be changed – Nataku62 Jan 17 '16 at 13:12
  • you can try `line.strip()` or `line.rstrip('\n')` – Wikunia Jan 17 '16 at 13:42
  • Thanks wikunia exactly what I needed to get it to work!!!! – Nataku62 Jan 20 '16 at 00:10

1 Answers1

0
final_list = []
with open("accounts.txt","r") as my_file:
    first_list = my_file.readlines() 
    for i in first_list: 
        final_list.append(i.strip())

change it to suit your needs, this removes any \n.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59