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

2019-01-02 17:15发布

This question already has an answer here:

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)

11条回答
情到深处是孤独
2楼-- · 2019-01-02 18:03

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

with open(filename) as f:
    mylist = f.read().splitlines() 
查看更多
爱死公子算了
3楼-- · 2019-01-02 18:04
from string import rstrip

with open('bvc.txt') as f:
    alist = map(rstrip, f)

Nota Bene: rstrip() removes the whitespaces, that is to say : \f , \n , \r , \t , \v , \x and blank ,
but I suppose you're only interested to keep the significant characters in the lines. Then, mere map(strip, f) will fit better, removing the heading whitespaces too.


If you really want to eliminate only the NL \n and RF \r symbols, do:

with open('bvc.txt') as f:
    alist = f.read().splitlines()

splitlines() without argument passed doesn't keep the NL and RF symbols (Windows records the files with NLRF at the end of lines, at least on my machine) but keeps the other whitespaces, notably the blanks and tabs.

.

with open('bvc.txt') as f:
    alist = f.read().splitlines(True)

has the same effect as

with open('bvc.txt') as f:
    alist = f.readlines()

that is to say the NL and RF are kept

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 18:04

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():
        print(apps.strip())
查看更多
初与友歌
5楼-- · 2019-01-02 18:05

After opening the file, list comprehension can do this in one line:

fh=open('filename')
newlist = [line.rstrip() for line in fh.readlines()]
fh.close()

Just remember to close your file afterwards.

查看更多
旧时光的记忆
6楼-- · 2019-01-02 18:08

for each string in your list, use .strip() which removes whitespace from the beginning or end of the string:

for i in contents:
    alist.append(i.strip())

But depending on your use case, you might be better off using something like numpy.loadtxt or even numpy.genfromtxt if you need a nice array of the data you're reading from the file.

查看更多
登录 后发表回答