Dylan
Dylan

Reputation: 11

Writing from a text file to SQL using Python

Hey I was just wondering if anyone would be able to help with writing the contents of a series of text files (e.g. activities.txt, sports.txt) (each has has a number, a tab, and a value (e.g. 90 Badminton) in each row). I have already initialised the database connection and have the table in SQL made ready to go.

Any help would be greatly appreciated!

Thanks

Upvotes: 0

Views: 6079

Answers (1)

Bryan
Bryan

Reputation: 6699

If I understand this correctly then the following snippet should get you started. I'm going to assume you already have access to a cursor...

category = "Sports"
with open("sports.txt", "r") as sports:
    lines = sports.readlines()

for line in lines:
    # Split the line on whitespace
    data = line.split()
    number = data[0]
    value = data[1]

    # Put this through to SQL using an INSERT statement...
    cursor.execute("""INSERT INTO tablename (person_id, category, type)
                   VALUES(%s, %s, %s)""", (number, category, value))

Upvotes: 1

Related Questions