Python 在 python 中遍历文件行时无法更改变量值

Python can't change value of variable while iterate through a file lines in python

我想检查 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。我认为问题是代码无法从内部更改 check 变量for 循环,但我不知道如何修复它。你能帮帮我吗?对不起,如果我的英语有任何误解。

line的值实际上以'\n'结尾。您应该检查 f'{devicename}\n' == linedevicename in line.

每行以\r\n\n结尾,但您可以删除换行符:

for line in [x.rstrip() for x in f]:

for line in f:  
    line = line.rstrip()
    ...

我无法重现您的代码。所以我做了一个类似的demo。

您可以删除 '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());