python 逐行读取文本文件
python read from text file line by line
我希望我的代码从文本文件中读取并将数据填充到列表中。
我要到达的代码:
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())
我希望我的代码从文本文件中读取并将数据填充到列表中。
我要到达的代码:
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())