0

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

2
  • 1
    Give examples of the input and output you want. Not just useful for us in helping, that's useful to you in designing a solution yourself. Commented May 27, 2011 at 0:59
  • I need to input the rows from the text files and output each piece of data to a specific column in the SQL table. For example, the table headers would be PersonId | Category | Type and the values would be 1 | Sports | Soccer. I'd get this data from the text files e.g. sports.txt "1 Soccer 2 Badminton 3 Football" etc Commented May 27, 2011 at 1:06

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

3 Comments

You'll want to make sure you handle the case where number, category and value have single quotes in them.
I was almost ready to upvote until I saw the unescaped strings going into the SQL. If one of the categories is "Bobby Tables' favorite strings" then you're going to have a problem...
The others are correct. I meant to make use of DB-API's parameter substitution. My post now reflects that...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.