问题描述
我只想获取第二个结果,num
打印并使用它。
savee1
是一个.txt文件
def copycoordinates():
savee1 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles",title="Choose FIRST File",filetypes=[("sii files","*.sii")])
savee2 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles",title="Choose SECOND File","*.sii")])
i1 = Label(frame5,text="Chosen FIRST File \n" + savee1)
i1.pack()
i2 = Label(frame5,text="Chosen SECOND File \n" + savee2)
i2.pack()
command=lambda:[save1()]
subprocess.Popen(["C:/SII_Decrypt.exe",savee1])
command=lambda:[save2()]
subprocess.Popen(["C:/SII_Decrypt.exe",savee2])
#time.sleep(1)
with open(savee1,"r+") as save1:
for num,line in enumerate(save1,1):
if "truck_placement:" in line:
print(num)
解决方法
results = list()
with open(savee1,"r+") as save1:
for num,line in enumerate(save1,1):
if "truck_placement:" in line:
print(num)
results.append(num)
print(results[1]) #this is the value you want
,
不确定文本文件中的内容,但是通常情况是以某种方式分隔的(换行符,制表符分隔,逗号分隔)。您应该对分隔的内容进行拆分,然后可以对结果列表进行索引。以下代码假定您想要的东西用换行符分隔:
with open(save1,"r+") as infile:
f=infile.read()
list_o_txt = f.split('\n')
print (list_o_txt[1])
如果要创建仅包含短语“ truck_placement”的文本的子列表
with open(save1,'r') as infile:
f=infile.read()
list_o_txt = f.split('\n') # produces a list
filtered_list = [line for line in list_o_txt if 'truck_placement' in line] #filters the list
print (filtered_list[1]) #prints the second item
,
如果您想参加第二场比赛,可以尝试:
with open(savee1,"r+") as save1:
match = 0
for num,1):
if 'truck_placement:' in line:
match += 1
if match == 2
print(num)
else:
continue
该数字将在第二个匹配项上显示。
肯定有更好的方法,但这是最简单的解决方案之一。