我有一个包含以下内容的文件:
name: Sam
placing: 2
quote: I'll win.
name: Jamie
placing: 1
quote: Be the best.
我希望通过python读取文件并将特定内容附加到列表中。我希望我的第一个列表包含:
rank = [['Sam', 2],['Jamie', 1]]
和第二个列表包含:
quo = ['I'll win','Be the best']
首先,我开始通过以下方式阅读该文件:
def read_file():
filename = open("player.txt","r")
playerFile = filename
player = [] #first list
quo = [] #second list
for line in playerFile: #going through each line
line = line.strip().split(':') #strip new line
print(line) #checking purpose
player.append(line[1]) #index out of range
player.append(line[2])
quo.append(line[3])
我在第一个附加中获得了超出范围的索引。我用':'分开了,但我似乎无法访问它。
答案 0 :(得分:0)
当 line =“name:Sam”时, line = line.strip()。split(':') 你会收到 ['name','Sam'] 所以首先附加应该有用。
第二个player.append(第[2]行无效。
正如zython在评论中所说,您需要知道文件的格式以及文件中的每个空行或其他更改,都会使脚本失败。
您应该以不同方式分析文件: 如果您可以依赖“名称”和“引用”始终是每个玩家数据中的现有字段这一事实,那么您应该查找此字段名称。
例如:
for line in file:
# Run on each line and insert to player list only the lines with "name" in it
if ("name" in line):
# Line with "name" was found - do what you need with it
player.append(line.split(":")[1])
答案 1 :(得分:0)
一些问题,
for
循环的单次迭代中读取三行数据。但这不起作用,因为循环和split
命令每次迭代只解析一行。从文件中读取单个条目需要三次循环迭代。line
只有一个值是空字符串。当你看到它时,忽略该行。player
。因此,您需要在上面声明该临时数组,首先使用name
字段填充,然后使用placing
字段填充,最后将其附加到player
。list[0]
,而不是list[1]
答案 2 :(得分:0)
试试这段代码:
def read_file():
filename = open("player.txt", "r")
playerFile = filename
player = []
rank = []
quo = []
for line in playerFile:
value = line.strip().split(": ")
if "name" in line:
player.append(value[1])
if "placing" in line:
player.append(value[1])
if "quote" in line:
quo.append(value[1])
rank.append(player)
player = []
print(rank)
print(quo)
read_file()
答案 3 :(得分:0)
我认为您对如何检查一行并根据其包含的内容将行内容添加到两个列表感到困惑。您可以使用in
检查您当前在哪条线上。假设您的文本文件与相关内容相同,则可以正常工作。
rank, quo = [], []
for line in playerFile:
splitted = line.split(": ")
if "name" in line:
name = splitted[1]
elif "placing" in line:
rank.append([name, splitted[1]])
elif "quote" in line:
quo.append(splitted[1])
print(rank) # [['Sam', '2'],['Jamie', '1']]
print(quo) # ["I'll win",'Be the best']