我有一个。txt文件的值。

这些值如下所示:

Value1
Value2
Value3
Value4

我的目标是将值放在一个列表中。当我这样做时,列表看起来像这样:

['Value1\n', 'Value2\n', .〕

\n不需要。

这是我的代码:

t = open('filename.txt')
contents = t.readlines()

当前回答

我使用strip函数来消除换行符,因为分割行会在4 gb的文件上抛出内存错误。

示例代码:

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

其他回答

我使用strip函数来消除换行符,因为分割行会在4 gb的文件上抛出内存错误。

示例代码:

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

最简单的方法是写入file.readline()[0:-1] 这将读取除最后一个字符(换行符)以外的所有内容。

这应该是你想要的(文件内容在一个列表中,按行,不\n)

with open(filename) as f:
    mylist = f.read().splitlines() 

你可以使用.rstrip('\n')只删除字符串末尾的换行符:

for i in contents:
    alist.append(i.rstrip('\n'))

这将保留所有其他空白。如果您不关心行首和行尾的空白,那么这个巨大的重锤就被称为.strip()。

但是,由于您正在从文件中读取并将所有内容拉入内存,因此最好使用str.splitlines()方法;这将在行分隔符上分割一个字符串,并返回一个没有这些分隔符的行列表;在file.read()结果上使用这个,而完全不使用file.readlines():

alist = t.read().splitlines()
with open('D:\\file.txt', 'r') as f1:
    lines = f1.readlines()
lines = [s[:-1] for s in lines]