在Python中如何将文件附加到列表中?
我有一个名为“scores.txt”的示例文件,其中包含以下值:在Python中如何将文件附加到列表中?,python,list,python-3.x,append,Python,List,Python 3.x,Append,我有一个名为“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) 这部分起作用,但由于某些原因
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)
这部分起作用,但由于某些原因,它不能正常工作。它只是将所有值粘贴到一个索引中,而不是单独的索引中。如何使所有的值都被放入各自的单独索引中?CSV数据以逗号分隔。最简单的方法是使用: 否则,请拆分这些值。您读取的每一行都是一个字符串,数字之间带有“,”字符:
all_values = []
with open('scores.txt', newline='') as infile:
for line in infile:
all_values.extend(line.strip().split(','))
无论哪种方式,所有_值都以字符串列表结束。如果所有值仅由数字组成,则可以将其转换为整数:
all_values.extend(map(int, row))
或
这是一种在不使用任何外部软件包的情况下实现这一点的有效方法:
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
只需在每一行使用逗号拆分,并将返回的列表添加到您的分数列表中,如下所示:
opener = open('scores.txt','r')
score_list = []
for line in opener:
score_list.extend(map(int,line.rstrip().split(',')))
print( score_list )
您有一个列表,而不是数组。后者是,绝对有用。我可以问一下:“.rstrip”和“.split”函数是做什么的?Thanksure,rstrip函数使用您提供的第一个解决方案删除行尾和拆分,分离上的字符串。在reader=csvinfile:TypeError中给出了第13行:“module”对象是不可调用的错误。你知道为什么吗?@TeeKayM:因为我是个笨蛋,忘了.reader部分。你应该真正使用score\u list.extend或score\u list+=来避免一直创建新列表。@MartijnPieters谢谢。更新我的答案以使用扩展
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
opener = open('scores.txt','r')
score_list = []
for line in opener:
score_list.extend(map(int,line.rstrip().split(',')))
print( score_list )