【问题标题】:How to append from file into list in Python?如何从文件追加到 Python 中的列表中?
【发布时间】:2016-01-23 16:44:01
【问题描述】:

我有一个名为“scores.txt”的示例文件,其中包含以下值:

10,0,6,3,7,4

我希望能够以某种方式从行中获取每个值,并将其附加到列表中,使其变为sampleList = [10,0,6,3,7,4]

我已经尝试使用下面的代码来做到这一点,

score_list = []

opener = open('scores.txt','r')

for i in opener:
    score_list.append(i)

print (score_list)

这部分有效,但由于某种原因,它不能正确执行。它只是将所有值粘贴到一个索引中,而不是单独的索引中。我怎样才能使所有值都放入它们自己的单独索引中?

【问题讨论】:

标签: python list python-3.x append


【解决方案1】:

您有 CSV 数据(逗号分隔)。最简单的是使用csv module

import csv

all_values = []

with open('scores.txt', newline='') as infile:
    reader = csv.reader(infile)
    for row in reader:
        all_values.extend(row)

否则,拆分值。您阅读的每一行都是一个字符串,数字之间有',' 字符:

all_values = []

with open('scores.txt', newline='') as infile:
    for line in infile:
        all_values.extend(line.strip().split(','))

无论哪种方式,all_values 都会以 字符串列表 结束。如果您的所有值都仅由数字组成,则可以将它们转换为整数:

all_values.extend(map(int, row))

all_values.extend(map(int, line.strip().split(',')))

【讨论】:

  • 使用您提供的第一个解决方案会给我一个Line 13 in reader = csv(infile): TypeError: 'module' object is not callable 错误。你知道为什么会这样吗?
  • @TeeKayM:因为我是个笨蛋,忘记了.reader 部分。
【解决方案2】:

这是一种不使用任何外部包的有效方法:

with open('tmp.txt','r') as f:
    score_list = f.readline().rstrip().split(",")

# Convert to list of int
score_list = [int(v) for v in score_list]

print score_list

【讨论】:

  • 绝对有帮助。我能问一下:'.rstrip()' 和 '.split()' 函数有什么作用?谢谢
  • 当然,rstrip 函数会删除行尾,split(",") 会在 "," 上分隔一个字符串
【解决方案3】:

只需在每行的逗号上使用split,并将返回的列表添加到您的score_list,如下所示:

opener = open('scores.txt','r')
score_list = []

for line in opener:
    score_list.extend(map(int,line.rstrip().split(',')))

print( score_list )

【讨论】:

  • 您真的应该使用score_list.extend() 或使用score_list += 以避免一直创建新列表。
  • @MartijnPieters 谢谢。更新了我的答案以使用extend
猜你喜欢
  • 1970-01-01
  • 2016-06-02
  • 2021-01-09
  • 2013-11-08
  • 2021-12-26
  • 1970-01-01
  • 2018-11-13
  • 2017-02-06
  • 2017-07-17
相关资源
最近更新 更多