Max Paul
Max Paul

Reputation: 1

printing a list and removing the '\n' from each new line, giving error

Printing a list from a file and not allowing me to use .rstrip('/n'):

path =('debits.txt','r')


 f = open('debits.txt')
 read = f.readlines().rstrip('/n')

expecting me to print a nice clean list without the '\n' and each entry put into a list.

Upvotes: 0

Views: 41

Answers (3)

Djaouad
Djaouad

Reputation: 22776

First, readlines returns a list, so you need to apply rstrip to its elements, not to it, and, you're striping '/n' in your code (should be '\n'), finally, you're not using the path variable in open (not using it will not cause an error but you probably should use it since you defined it):

path =('a.txt', 'r')

with open(*path) as f:  #  use `with` to automatically close the file after reading
    read = [l.rstrip('\n') for l in f.readlines()]

One more note, you can just use l.rstrip() (no need for '\n') to remove whitespace.

Upvotes: 1

vendrediSurMer
vendrediSurMer

Reputation: 448

f.readlines() returns a list so iterate through that list instead:

f = open('debits.txt', 'r')
read = f.readlines()
for line in read:
    line = line.rstrip("\n")
    print(line)
f.close()

Upvotes: 0

Shan Ali
Shan Ali

Reputation: 564

rstrip() removes \n from strings not a list. That's why you are getting error. Use this while reading file:

with open('debits.txt') as f:
    alist = [line.rstrip() for line in f.readlines()]

Upvotes: 0

Related Questions