mardi 17 mars 2020

if loop does not end after return

Members,

i'm breaking my head for many hours, why my code isn't working.

I'm getting data from CSV file, and i'm trying to change one value, when two codes matches.

def mode(x):
for line in data_df['Bar_Code']:
    #print(line) ~ Line outputs the Barcodes in the Bar_Code Column of the CSV file.
    with open("Barcodes_to_match.txt") as barcodes:
        for barcode in barcodes:
            #print(barcode) ~ Outputs the Barcode that it need to be matched.
            if barcode == line:
                x = x.replace("True", "False")
                return x

data_df['Published'] = data_df['Published'].apply(lambda x: mode(x))

data_df.to_csv(('Products.csv'), encoding='UTF-8', quoting=csv.QUOTE_ALL, quotechar='"', index=None, sep=str(","))

The Product.csv file:

Bar_Code, Product, Published
BLA00BLA00, Product1, True
BLU00BLU00, Product2, False
BLI00BLI00, Product3, True
BLE00BLE00, Product4, False

Barcodes_to_match.txt:

BLA00BLA00
BLI00BLI00

So, i need to change the values for Product rows(BLA00BLA00 and BLI00BLI00) Published column to False

Can someone check my method to Replace the Values?

Thanks!

Edit: When i add print command, it seems that the code is stocked at the last match in endless loop.

if barcode == line:
   print(barcode + " = " + line)
   x = x.replace("True", "False")
   return x

Output:
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00

Aucun commentaire:

Enregistrer un commentaire