python逐行从文本文件中读取

问题描述 投票:1回答:2

我希望我的代码从文本文件中读取并将数据填充到列表中。

the Text file

我想输入的代码:

dataset = [['a', 'b', 'c'],
           ['b', 'c'],
           ['a', 'b', 'c'],
           ['d'],
           ['b', 'c']]

我已经尝试过此代码:

dataset = open(filename).read().split('\n')
for items in dataset:
        print(items)

result from printing the list

我的列表中包含空格,所以如何解决此问题?谢谢

python printing split anaconda filereader
2个回答
1
投票

此脚本将文件加载到dataset列表中:

dataset = []
with open(filename, 'r') as f_in:
    for items in f_in:
        dataset.append(items.split())

print(dataset)

打印:

[['a', 'b', 'c'], ['b', 'c'], ['a', 'b', 'c'], ['d'], ['b', 'c']]

1
投票

您可以逐行阅读,然后按单词拆分每行:

dataset = []
with open(filename, 'r') as fp:
    for line in fp.lines():
        dataset.append(line.split())
© www.soinside.com 2019 - 2024. All rights reserved.