簡體   English   中英

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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM