jeudi 30 mai 2019

Why is if-function not working, using two strings?

I try to compare two strings (one coming from a database - sqlite3 - via object.get() and the other one is coming from a cell in a csv file) within an if-clause using python (PyCharm). I want to insert the data (around 13.000 listings) from the csv file into a database/table. Problem is that one "csv-column" contains values which should refer to a foreign key table (already created). I don't understand why the two strings are not equal, although they should be. Perhaps you guys can help me with this issue. Thanks, nicdreifuss

I used cmd, opend a pyhton manage.py shell, imported all models from models and imported the python file which contains the function (works fine). Then I ran the function and the problem is that the condition b11==b12 is always NOT true, although seem to be equal. Therefore I always get to else and get the return = Its not working.

I tried to import the data without the if-clause and it works just fine, but I have to make a selection of the foreign Key in the table depending on what the value is in column 3 (index[2]). So infact there will be a b2, b3, b4...

def bula():
    file = open("C:\\Users\\...\\...\\postalcodes.csv", "r")
    rows = file.readlines()

    b1 = Bundesland.objects.get(bundesland="Berlin")

    for i in range(len(rows)):
        fields = rows[i].split(";")

        b11 = str(b1.bundesland)
        b12 = str(fields[2])

        print(b11, b12)
        print(type(b11), type(b12))

        if b11 == b12:
            print("Its working")
            das = SPB(stadt=fields[0], plz=fields[1], bundesland=b1)
            das.save()

        else:
            print("Its not working")
            pass

from main.models import* #<<<--- import "SPB" model to get data from Foreign Key table from main.test import* #<<<---here is the function bula() #<<<--- run function

output is the following:

Berlin Berlin

Its not working Berlin Berlin

Its not working

expected would be output:

Berlin Berlin

Its working Berlin Berlin

Its working

Aucun commentaire:

Enregistrer un commentaire