我希望我的代码从文本文件中读取并将数据填充到列表中。
我想输入的代码:
dataset = [['a', 'b', 'c'],
['b', 'c'],
['a', 'b', 'c'],
['d'],
['b', 'c']]
我已经尝试过此代码:
dataset = open(filename).read().split('\n')
for items in dataset:
print(items)
我的列表中包含空格,所以如何解决此问题?谢谢
此脚本将文件加载到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']]
您可以逐行阅读,然后按单词拆分每行:
dataset = []
with open(filename, 'r') as fp:
for line in fp.lines():
dataset.append(line.split())