Python 使用 .readlines() 时摆脱 \n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15233340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting rid of \n when using .readlines()
提问by TDNS
I have a .txt file with values in it.
我有一个带有值的 .txt 文件。
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', ...]
['Value1\n', 'Value2\n', ...]
The \nis not needed.
该\n是没有必要的。
Here is my code:
这是我的代码:
t = open('filename.txt', 'r+w')
contents = t.readline()
alist = []
for i in contents:
alist.append(i)
回答by askewchan
for each string in your list, use .strip()which removes whitespace from the beginning or end of the string:
对于列表中的每个字符串,使用.strip()它从字符串的开头或结尾删除空格:
for i in contents:
alist.append(i.strip())
But depending on your use case, you might be better off using something like numpy.loadtxtor even numpy.genfromtxtif you need a nice array of the data you're reading from the file.
但是根据您的用例,您可能最好使用类似的东西,numpy.loadtxt或者即使numpy.genfromtxt您需要从文件中读取的数据的漂亮数组。
回答by Martijn Pieters
You can use .rstrip('\n')to onlyremove newlines from the end of the string:
您可以使用.rstrip('\n')到只能从字符串的结尾去掉换行符:
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().
这使所有其他空白保持不变。如果您不关心行首和行尾的空格,那么大重锤称为.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:
但是,由于您正在从文件中读取并且无论如何都将所有内容拉入内存,因此最好使用该str.splitlines()方法;这会在行分隔符上拆分一个字符串,并返回没有这些分隔符的行列表;在file.read()结果上使用它并且根本不使用file.readlines():
alist = t.read().splitlines()
回答by hughdbrown
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]
回答by eyquem
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, \xand 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.
Nota Bene:rstrip()删除空格,即 : \f, \n, \r, \t, \v,\x和 blank ,
但我想您只对保留行中的重要字符感兴趣。然后,仅仅map(strip, f)会更适合,也删除标题空格。
If you really want to eliminate only the NL \nand RF \rsymbols, do:
如果您真的只想消除 NL\n和 RF\r符号,请执行以下操作:
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.
没有传递参数的 splitlines() 不保留 NL 和 RF 符号(Windows 在行尾记录带有 NLRF 的文件,至少在我的机器上)但保留其他空格,特别是空格和制表符。
.
.
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
也就是说保留了 NL 和 RF
回答by user3131651
This should do what you want (file contents in a list, by line, without \n)
这应该做你想做的(列表中的文件内容,按行,没有\n)
with open(filename) as f:
mylist = f.read().splitlines()
回答by micsthepick
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.
它不适用于单行文本之间的空格,但看起来您的示例文件可能没有空格分割值。这是一个简单的解决方案,它返回一个准确的值列表,并且不添加空字符串:''对于每个空行,例如文件末尾的换行符。
回答by jperezmartin
with open('D:\file.txt', 'r') as f1:
lines = f1.readlines()
lines = [s[:-1] for s in lines]
回答by anon
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.
最简单的方法是编写file.readline()[0:-1]This 将读取除最后一个字符(即换行符)之外的所有内容。
回答by geo1230
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.
首先,我会从“with”语句开始,因为它确保正确打开/关闭文件。
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 intinstead of floatif you want to convert to integer.
如果要转换为整数,请使用int代替float。
It's my first answer in SO, so sorry if it's not in the proper formatting.
这是我在 SO 中的第一个答案,如果格式不正确,请见谅。
回答by Lisle
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.
请记住之后关闭您的文件。

