MapInfo Pro

 View Only

MapInfo Monday: Merging Tables with Python

  • 1.  MapInfo Monday: Merging Tables with Python

    Employee
    Posted 24 days ago

    In last week's #MapInfo Monday post, we discussed how to merge several tables into one when the tables have the same table structure.

    I showed you a manual way and a semi-automated way using MapBasic.

    Today, we will make it completely automated with Python. You are up for quite an Easter egg.

    Happy #MapInfoMonday

    Merging Tables through a Python Script

    Python to the rescue!

    Python scripting in MapInfo Pro comes with several benefits over the standard MapBasic scripting.

    In this case, the support for looping makes all the difference.

    You can't loop in a MapBasic script through the MapBasic window or the SQL Window. That is only possible in a compiled MapBasic application.

    Python, on the other hand, does allow loops.

    Through Python, you have access to the MapInfo Data Access Library, which gives you a different way of working in MapInfo Pro. Especially because it's using an Object Orientated way of programming, which is quite different to the normal MapBasic language.

    You can the pro object in Python to access the MapInfo application, and from this access the tables through the Catalog.

    In this manner, I can get to the name of the last table in the Catalog and store this name in the variable tabIntoName.

    Now, I can loop over all the tables in the Catalog. I get the name of the table, and if it's not the same as the name stored in the variable tabIntoNameI execute a MapBasic command to insert this table into the last table. You can use the method RunMapBasicCommand to send MapBasic statements to MapInfo Pro for execution.

    When you run the script via the Run button, all tables are merged into the output table.
    Here is the Python script:

    numTables = pro.Catalog.Tables.Count
    tabIntoName = pro.Catalog.Tables[numTables -1].Alias
    print("Resulting Table: {0}".format(tabIntoName))

    for tab in pro.Catalog.Tables:
        tabName = tab.Alias
        print("Input Table: {0}".format(tabName))
        if tabName != tabIntoName:
            print("Insert Into {0} Select * From {1}".format(tabIntoName, tabName))
            pro.RunMapBasicCommandEx("Insert Into {0} Select * From {1}".format(tabIntoName, tabName))
            
    print("Done!")

    Have you started using Python inside MapInfo Pro?



    ------------------------------
    Peter Horsbøll Møller
    Principal Presales Consultant | Distinguished Engineer
    Precisely | Trust in Data
    ------------------------------