Getting rid of \n when using .readlines()

TDNS picture TDNS · Mar 5, 2013 · Viewed 348.2k times · Source

I have a .txt file with values in it.

The values are listed like so:

Value1
Value2
Value3
Value4

My goal is to put the values in a list. When I do so, the list looks like this:

['Value1\n', 'Value2\n', ...]

The \n is not needed.

Here is my code:

t = open('filename.txt', 'r+w')
contents = t.readline()

alist = []

for i in contents:
    alist.append(i)

Answer

user3131651 picture user3131651 · Dec 24, 2013

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

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