Python 在迭代文件行时无法更改变量的值

标签 python python-3.x adb

我想检查 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/

相关文章:

python - 通过python从名称列表中提取最后两个字母

python - 如何删除 BigTable GCP 中的过滤行

python - "[Errno 13] Permission denied"仅在 Ubuntu 服务器上尝试更新/更改文档时

python - 是否可以循环遍历 Amazon S3 存储桶并使用 Python 计算其文件/ key 中的行数?

python - 是否可以强制 Numpy 在进行类型转换时使用 cutout 而不是溢出?

python - 全局控制点 : testing an application which uses ndb (no module named `google.appengine` )

python - 在 Windows 上检测插入的 USB

android - 从 adb 获取包的可启动 Activity 名称

android - adb logcat -f log.txt 错误: couldn't open output file: Read-only file system

android - 无法通过 ADB 通过 wifi 连接到 Android - 我需要 root 访问权限吗?