【问题标题】:How can I get python to read each line in a txt file and make seperate lists?如何让 python 读取文本文件中的每一行并制作单独的列表?
【发布时间】:2019-12-03 07:20:16
【问题描述】:

假设我有一个包含一些整数的 .txt 文件。

#txt file called ints.txt

1,3
4
5,6

如何让 python 读取每一行并将它们放入单独的列表中?

我正在寻找的输出:

['1','3']
['4']
['5','6']

我尝试了这段代码,但它只将 txt 文件的第一个元素打印为列表。我也希望它打印后续元素。

x = open("ints.txt", "r")
x = x.readline()
x = x.strip()
x = x.split(" ")


for i in x:

    print(x)

Output:
['1','3']
['1','3']

感谢帮助,我的朋友们:)

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    试试这个:

    with open('file/path') as f:
        lines = [i.strip().split(',') for i in f.readlines() if i.strip()]
    

    要打印每行中的列表列表,请执行以下操作:

    print(*lines, sep='\n')
    

    【讨论】:

    • 这很棒,尽管它以一个包含多个列表的列表的形式提供输出。是否可以将每一行打印为单独的列表?
    【解决方案2】:

    试试 readlines 方法。类似的东西。

    with open("ints.txt", "r") as f:
        for line in f.readlines():
            items = line.split(',')
    

    【讨论】:

      【解决方案3】:

      这对你有帮助

      `with open("test.txt", "r") as openfile:
          for line in openfile:
              new_list = [x for x in line.split(" ")]
              print(new_list)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 2013-11-20
        • 1970-01-01
        • 2011-05-21
        • 2014-05-11
        • 2019-05-23
        • 1970-01-01
        相关资源
        最近更新 更多