[英]Reading and taking specific file contents in a list in python
我有一個文件包含:
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])
我在第一個附錄中得到的索引超出范圍。 我已用':'分開,但似乎無法訪問它。
當您執行line = line.strip()。split(':')時,當line =“ name:Sam”時,您會收到['name','Sam'],因此應先執行附加操作。
第二個player.append(line [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])
一些問題,
for
循環的單次迭代中讀取三行數據。 但這是行不通的,因為循環和split
命令在每次迭代中僅解析一行。 要從文件中讀取一個條目,將需要進行三個循環迭代。 line
只有一個值,它是一個空字符串。 看到該行時,請忽略該行。 player
。 因此,您需要在上面聲明該臨時數組,首先使用name
字段填充,然后使用placing
字段填充,最后將其附加到player
。 list[0]
而不是list[1]
試試這個代碼:
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()
我認為您對如何檢查行並將行中的內容基於行包含的內容添加到兩個列表感到困惑。 您可以使用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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.