我想检查 txt 文件的每一行,看看所连接设备的序列号是否存在。这是我的代码:
from ppadb.client import Client as AdbClient
# Open the file in append & read mode ('a+')
def checkDeviceName(devicename):
with open('deviceList.txt', "a+") as f:
check = 0
for line in f:
if devicename == line:
check += 1
if check == 0:
f.write('\n')
f.write(devicename)
else:
print('Device Name: ', devicename)
client = AdbClient(host="127.0.0.1", port=5037)
devices = client.devices()
listOutput = []
for device in devices:
output = device.shell("getprop | grep -e 'serialno'")
print(output)
listOutput.append(output[21:35])
print(listOutput)
i = 0
while i < len(listOutput):
checkDeviceName(listOutput[i])
i += 1
问题是,即使所连接的真实设备的序列号已经存在于 deviceList.txt 文件中,程序仍然将其附加在文件末尾。我尝试打印 check 变量,但它始终保持为 0。我认为问题是代码无法从 for 循环< 内部更改 check 变量/em>,但我不知道如何解决它。你能帮我一下吗?抱歉,如果我的英语造成任何误解。
最佳答案
我无法重现您的代码。所以我做了一个类似的演示。
您可以删除“is_new_device”变量。
import os, random
global_filename="deviceList.txt";
def checkDeviceName(devicename):
is_new_device=False;
fp=open(global_filename,"+a"); fp.seek(0); lines=fp.readlines();
if len(lines)==0 or all([devicename not in line for line in lines]):
fp.write(f"{devicename}\n"); is_new_device=True;
fp.close();
return is_new_device
random.seed(1234);
for i in range(5):
random_device_input = random.choice(["123.123.123", "123.321.132", "172.111.222.333"])
is_new_device = checkDeviceName(random_device_input);
print(f"\n#{i} input, is_new = {random_device_input:20s}, {is_new_device}");
fp=open(global_filename,"r"); lines=fp.readlines(); fp.close();
for line in lines: print(line.strip());
关于Python 在迭代文件行时无法更改变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71506431/