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
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))
精彩评论