如何使用python在文件中查找特定范围?

2024-04-24 23:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个文件中找到一个与特定MAC地址相等的特定范围。你知道吗

代码如下:

sensortag=0
while sensortag != "B4:99:4C:64:33:E0":
    os.system("hcitool lescan> scan.txt & pkill --signal SIGINT hcitool")
    scan = open("scan.txt", "r")
    readscan = scan.read()

    #read range 40-56 in file, NOTE: THIS WORKS IF I JUST KEEP IT if readscan[40] == "B", b being the start of the MAC address
    if readscan[40:56] == "B4:99:4C:64:33:E0":
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"

代码只是无限循环。你知道吗

更新:感谢jkalden,我的代码现在可以使用以下解决方法:

if "B4:99:4C:64:33:E0" in readscan:
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"

我使用for循环打印索引号和相应的值,以验证它是否是我需要的40-56范围。你知道吗

for index, i in enumerate(readscan):
    print index, i

Tags: the代码intxtreadscanifmac
3条回答

问题是循环没有结束。试试这个

os.system("hcitool lescan> scan.txt & pkill  signal SIGINT hcitool")
found = False
with open('scan.txt') as fin:
    for line in fin:
        if line[40:56] == 'B4:99:4C:64:33:E0':
            found = True
            break

if found:
    print "SensorTag found."
import re
os.system("hcitool lescan> scan.txt & pkill  signal SIGINT hcitool")
scan = open("scan.txt", "r")
readscan = scan.read()

all_Mac = re.findall("([0-9A-F]{2}(?::[0-9A-F]{2}){5})",readscan)
if 'B4:99:4C:64:33:E0' in all_Mac:
    print "Sensor tag found"

我用regexto找到所有的macaddress

多亏了jkalden,我的代码现在可以解决这个问题:

if "B4:99:4C:64:33:E0" in readscan:
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"

相关问题 更多 >