我想判断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 loop内部更改check变量,但我不知道如何修复它.你能帮帮我吗?对不起,如果我的英语有任何误解.

推荐答案

你的代码对我来说是不可复制的.所以我做了一个类似的演示.

您可以删除'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相关问答推荐

七段显示不完整

Pandas 修改原始excel

如何确保Flask应用程序管理面板中的项目具有单击删除功能?

使用Python从HTTP打印值

为什么我的代码会进入无限循环?

仅对matplotlib的条标签中的一个条标签应用不同的格式

为什么基于条件的过滤会导致pandas中的空数据框架?

在应用循环中间保存pandas DataFrame

使用polars .滤镜进行切片速度比pandas .loc慢

使用SciPy进行曲线匹配未能给出正确的匹配

比较两个数据帧并并排附加结果(获取性能警告)

如何使用pandasDataFrames和scipy高度优化相关性计算

为什么符号没有按顺序添加?

avxspan与pandas period_range

Django—cte给出:QuerySet对象没有属性with_cte''''

如何在Python中使用另一个数据框更改列值(列表)

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

重置PD帧中的值

在Admin中显示从ManyToMany通过模型的筛选结果