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 17:46
with open('D:\\file.txt', 'r') as f1:
    lines = f1.readlines()
lines = [s[:-1] for s in lines]
查看更多
听够珍惜
3楼-- · 2019-01-02 17:48

I recently used this to read all the lines from a file:

alist = open('maze.txt').read().split()

or you can use this for that little bit of extra added safety:

with f as open('maze.txt'):
    alist = f.read().split()

It doesn't work with whitespace in-between text in a single line, but it looks like your example file might not have whitespace splitting the values. It is a simple solution and it returns an accurate list of values, and does not add an empty string: '' for every empty line, such as a newline at the end of the file.

查看更多
浮光初槿花落
4楼-- · 2019-01-02 17:50

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]
查看更多
春风洒进眼中
5楼-- · 2019-01-02 17:53

The easiest way to do this is to write file.readline()[0:-1] This will read everything except the last character, which is the newline.

查看更多
若你有天会懂
6楼-- · 2019-01-02 17:55

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()
查看更多
栀子花@的思念
7楼-- · 2019-01-02 17:59

I had the same problem and i found the following solution to be very efficient. I hope that it will help you or everyone else who wants to do the same thing.

First of all, i would start with a "with" statement as it ensures the proper open/close of the file.

It should look something like this:

with open("filename.txt", "r+") as f:
    contents = [x.strip() for x in f.readlines()]

If you want to convert those strings (every item in the contents list is a string) in integer or float you can do the following:

contents = [float(contents[i]) for i in range(len(contents))]

Use int instead of float if you want to convert to integer.

It's my first answer in SO, so sorry if it's not in the proper formatting.

查看更多
登录 后发表回答