【问题标题】:How do you read lines from a .txt file? [closed]如何从 .t​​xt 文件中读取行? [关闭]
【发布时间】:2012-11-18 13:40:08
【问题描述】:

我有一个 .txt 文件,其中包含 100 个 50 位数字。每个数字位于不同的行。

文件示例:

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
#95 more numbers

我希望能够在打开文件后将每个数字附加到列表中。我该怎么做?

我知道如何打开文件:fo = open('file_name', 'r')。以及最后如何关闭:fo.close().

提前致谢!

【问题讨论】:

  • 到目前为止你尝试过什么?这是基本文件 I/O,答案可以在 Python 文档和教程中找到。
  • 让我猜猜:Project Euler #13?

标签: python text io


【解决方案1】:

您可以非常轻松地遍历文件中的行:

for line in fo:
    # Do whatever with the line

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      这是我能想到的最简单的方法:

      with open('numbers.txt') as file:
          lst = [line.strip() for line in file]
      

      【讨论】:

      • 谢谢。如果您实际上想要一个整数列表而不是字符串,请改用[int(line) for line in file]
      猜你喜欢
      • 2014-03-17
      • 2016-05-29
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      相关资源
      最近更新 更多