从文件中读取行并将其存储在列表中

问题描述 投票:0回答:1

我正在从文本文件中读取行,并且我希望列表中的每一行都成为数组中不同元素的一部分。

with open("diceRoll.txt","r") as x_file:
    contents = x_file.readlines()

oneScore = contents[count-1]
oneScore = oneScore.split(" ")
print(oneScore)
n = oneScore[0] + " " + oneScore[

当我运行程序一次时,得到以下响应:

['i', '68']

当我两次运行程序时,得到以下响应:

['i', '68j', '22']

如何更改代码,以便在两次运行程序时收到68, j,,而不是'68j'

python arrays list file
1个回答
0
投票
lines_list=[line.split(“ “) for line in open(“diceRoll.txt”,”r”)]
last_line=lines_list[-1]

应将文件的行作为列表的清单,并给您文件的最后一行。

© www.soinside.com 2019 - 2024. All rights reserved.