我只想得到第二个结果,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", filetypes=[("sii files", "*.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)
如果你的意思是想要第二场比赛,你可以尝试:
with open(savee1, "r+") as save1:
match = 0
for num, line in enumerate(save1, 1):
if 'truck_placement:' in line:
match += 1
if match == 2
print(num)
else:
continue
数字将打印在第二场比赛上。
肯定有更好的方法,但这是最简单的解决方案之一。
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