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

Time:03-17

I want to check every single line of an txt file to see if the serial numbers of connected devices existed. Here is my code:

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

The problem is even when the serial numbers of real devices connected is already existed in deviceList.txt file, the program still append it at the end of file. I tried to print out check variable but it always remains at 0. I think the problem is the code can't change the check variable from inside for loop, but I don't know how to fix it. Can you please help me out ? Sorry if my English make any misunderstood.

CodePudding user response:

The value of line actually ends with a '\n'. You should either check if f'{devicename}\n' == line or if devicename in line.

CodePudding user response:

Each line ends with \r\n or \n, but you can remove the line breaks:

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

or

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

CodePudding user response:

Your code is not reproducible to me. So I make a similar demo.

You can remove 'is_new_device' variable.

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());
  • Related