我正在制作一个与Xbee和python有关的应用程序,在这里我需要从文本文件读取数据,然后从文本文件中找出最大路由器值。 我的文本文件包含以下数据:
0013A20040C8316D - 0 0013A20040C8315B - 3 0013A20040C8316D - 1 0013A20041C8315B - 5 0013A20040C8316D - 4 0013A20045C8315B - 7
我尝试了以下代码:
file= open("myFile.txt","r")
dataRead= file.read()
dataReadInString= str(dataRead)
dataReadAfterRemovingString= dataReadInString.replace(" ","")
#print(dataReadInString)
print(dataReadAfterRemovingString)
Is there some way to get the value of 7(i.e, the highest number) from the textfile by reading the textfile. I am new to python . Please help.
答案 0 :(得分:0)
我会尽可能回答清楚。
我们将假定您的文件为常规方案:id1 - name1 id2 - name2 ...
下面是代码的详细信息:
file= open("myFile.txt","r")
# read file
dataReadInString = file.read()
# Remove line return
dataReadInString = dataReadInString.replace("\n", "")
print(dataReadInString)
# Create list for each element (id + name)
dataReadAfterRemovingString = dataReadInString.split(" ")
print(dataReadAfterRemovingString)
# New list that will have the ids
list_number = []
# Iterate for each element
for mot in dataReadAfterRemovingString:
# Create list with [id, name]
list_elt = mot.split(" - ")
# Append to the list of id the current id
list_number.append(list_elt[0])
# Display list of ID
print(list_number)
# ['0013A20040C8316D', '0013A20040C8315B', '0013A20040C8316D', '0013A20041C8315B', '0013A20045C8315B']
希望这个答案,任何问题,提出评论。