Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python在文件中查找特定范围?_Python_Linux_Unix - Fatal编程技术网

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

如何使用python在文件中查找特定范围?,python,linux,unix,Python,Linux,Unix,我试图在文件中找到与特定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

我试图在文件中找到与特定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

问题是,当循环没有结束时,您正在进行。试试这样的

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."

我使用regexto查找所有macaddress

多亏了jkalden,我的代码现在可以使用以下解决方法:

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

我在这里没有看到任何问题。我已经更新了标题:如何使用python在文件中查找特定范围?我不确定我是否正确,但是如果readscan:print“SensorTag found.”中的“B4:99:4C:64:33:E0”是如何的??完美!如果readscan:print“SensorTag found”中的“B4:99:4C:64:33:E0”,SensorTag=“B4:99:4C:64:33:E0”有效!谢谢你,杰卡登@JonathanDavies检查代码这不起作用。如果为:if readscan[40]=“B”,则while循环结束。要查找的单个值,而不是范围[40:56]
if "B4:99:4C:64:33:E0" in readscan:
        print "SensorTag found."
        sensortag = "B4:99:4C:64:33:E0"