我有一个 .txt 文件,其中包含值。
这些值如下所示:
Value1
Value2
Value3
Value4
我的目标是将值放入列表中。当我这样做时,列表如下所示:
['Value1\n', 'Value2\n', ...]
\n
不需要。
这是我的代码:
t = open('filename.txt', 'r+w')
contents = t.readline()
alist = []
for i in contents:
alist.append(i)
我有一个 .txt 文件,其中包含值。
这些值如下所示:
Value1
Value2
Value3
Value4
我的目标是将值放入列表中。当我这样做时,列表如下所示:
['Value1\n', 'Value2\n', ...]
\n
不需要。
这是我的代码:
t = open('filename.txt', 'r+w')
contents = t.readline()
alist = []
for i in contents:
alist.append(i)
这应该做你想要的(列表中的文件内容,按行,不带 \n)
with open(filename) as f:
mylist = f.read().splitlines()
我会这样做:
alist = [line.rstrip() for line in open('filename.txt')]
或者:
with open('filename.txt') as f:
alist = [line.rstrip() for line in f]
您可以使用.rstrip('\n')
仅从字符串末尾删除换行符:
for i in contents:
alist.append(i.rstrip('\n'))
这使所有其他空白保持不变。如果您不关心行首和行尾的空格,则称为大重锤.strip()
。
但是,由于您正在从文件中读取并将所有内容都拉入内存,因此最好使用该str.splitlines()
方法;这会在行分隔符上拆分一个字符串并返回没有这些分隔符的行列表;在file.read()
结果上使用它并且根本不使用file.readlines()
:
alist = t.read().splitlines()
打开文件后,列表推导可以在一行中完成:
fh=open('filename')
newlist = [line.rstrip() for line in fh.readlines()]
fh.close()
请记住之后关闭您的文件。
我使用 strip 函数来摆脱换行符,因为拆分行在 4 gb 文件上引发内存错误。
示例代码:
with open('C:\\aapl.csv','r') as apple:
for apps in apple.readlines():
print(apps.strip())
对于列表中的每个字符串,使用.strip()
它从字符串的开头或结尾删除空格:
for i in contents:
alist.append(i.strip())
但是根据您的用例,您最好使用类似的东西,numpy.loadtxt
或者即使numpy.genfromtxt
您需要一个很好的从文件中读取的数据数组。
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
我遇到了同样的问题,我发现以下解决方案非常有效。我希望它会帮助你或其他想要做同样事情的人。
首先,我将从“with”语句开始,因为它确保文件的正确打开/关闭。
它应该看起来像这样:
with open("filename.txt", "r+") as f:
contents = [x.strip() for x in f.readlines()]
如果您想将这些字符串(内容列表中的每个项目都是一个字符串)转换为整数或浮点数,您可以执行以下操作:
contents = [float(contents[i]) for i in range(len(contents))]
如果要转换为整数,请使用int
而不是。float
这是我在 SO 中的第一个答案,如果格式不正确,很抱歉。
我最近用它来读取文件中的所有行:
alist = open('maze.txt').read().split()
或者您可以使用它来增加一点额外的安全性:
with f as open('maze.txt'):
alist = f.read().split()
它不适用于单行文本之间的空格,但看起来您的示例文件可能没有空格分隔值。这是一个简单的解决方案,它返回一个准确的值列表,并且不添加空字符串:''
对于每个空行,例如文件末尾的换行符。
with open('D:\\file.txt', 'r') as f1:
lines = f1.readlines()
lines = [s[:-1] for s in lines]
最简单的方法是编写file.readline()[0:-1]
This 将读取除最后一个字符(即换行符)之外的所有内容。