python – Getting rid of n when using .readlines()

python – Getting rid of n when using .readlines()

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

with open(filename) as f:
    mylist = 

Id do this:

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


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

python – Getting rid of n when using .readlines()

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

for i in contents:

This leaves all other whitespace intact. If you dont 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 result and dont use file.readlines() at all:

alist =

Leave a Reply

Your email address will not be published. Required fields are marked *