Coder Perfect

When using.readlines(), removing the n [duplicate]


I have a.txt file that contains values.

The following is a list of the values:


My goal is to make a list of the values. When I do so, the following appears on the list:

[‘Value1\n’, ‘Value2\n’, …]

The n isn’t required.

My code is as follows:

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

alist = []

for i in contents:

Asked by TDNS

Solution #1

This should fulfill your requirements (file contents in a list, by line, without \n)

with open(filename) as f:
    mylist = 

Answered by user3131651

Solution #2

I’d do this:

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


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

Answered by hughdbrown

Solution #3

To remove only newlines from the end of a string, use.rstrip(‘n’):

for i in contents:

All other whitespace is unaffected. The huge heavy hammer is called if you don’t care about whitespace at the beginning and end of your lines. strip().

However, since you’re reading from a file and will be storing everything in memory, you should use the str.splitlines() method, which splits a string along line separators and gives a list of lines without those separators; apply this on the file. Instead of using file.readlines(), read() the result:

alist =

Answered by Martijn Pieters

Solution #4

List comprehension may perform this in one line after opening the file:

newlist = [line.rstrip() for line in fh.readlines()]

Just remember to save your work when you’re done.

Answered by Lisle

Solution #5

I used the strip function to get rid of newline character as split lines was throwing memory errors on 4 gb File.

Sample Code:

with open('C:\\aapl.csv','r') as apple:
    for apps in apple.readlines():

Answered by Yogamurthy

Post is based on