我有一个。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())
with open('D:\\file.txt', 'r') as f1:
    lines = f1.readlines()
lines = [s[:-1] for s in lines]

我会这样做:

alist = [line.rstrip() for line in open('filename.txt')]

or:

with open('filename.txt') as f:
    alist = [line.rstrip() for line in f]

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

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

我有同样的问题,我发现下面的解决方案是非常有效的。我希望它能帮助你或其他想做同样事情的人。

首先,我将以“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里的第一个答案,如果格式不对,很抱歉。