Getting rid of \n when using .readlines() [duplicate] Getting rid of \n when using .readlines() [duplicate] python python

Getting rid of \n when using .readlines() [duplicate]


This should do what you want (file contents in a list, by line, without \n)

with open(filename) as f:    mylist = f.read().splitlines() 


I'd do this:

alist = [line.rstrip() for line in open('filename.txt')]

or:

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


You can use .rstrip('\n') to only remove newlines from the end of the string:

for i in contents:    alist.append(i.rstrip('\n'))

This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip().

However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines() method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read() result and don't use file.readlines() at all:

alist = t.read().splitlines()