Python writing results out to a file
Question: I have the following script which thanks to the help of everyone is almost
done as it now prints out the results to the screen. I am also looking to add
one more step which will take this same screen output and dump it to a text
file.

I thought this was done with `file.write()`

but dont know how to get it to write the information from results to a file.
Please help, I am very new to python so I am a bit lost and trying to figure
it out from the book.

This now prints out but just the last line of what is being returned by the
query. Ultimately it is probably just printing one line and then overwriting
it again and again so I need it to print the whole of the fetch all or results

    
    
    import adodbapi
    
    # Connect to the SQL DB    
    conn = adodbapi.connect("Provider=SQLOLEDB; SERVER=xx.x.xx.x; Initial Catalog=master_db;User Id=user; Password=pass; ")
    curs = conn.cursor()
    
    # Execute SQL procedure things_referencing"    
    curs.execute('util.things_procedure', )
    results = curs.fetchall()
    
    for row in results:
        print row
    
    f = open('test.txt', 'w')
    s = str(row)
    f.write(s)
    f.close()
    
    conn.close()
    


Answer: Each "row" in the "results" tuple is a record tuple. How you want to format
this data is up to you, but at the most basic level you can convert it to a
string with `str(row)`

Now go read the python docs on how to read and write files:  
<http://docs.python.org/tutorial/inputoutput.html>

**Update**

Referring to your new code example, you are doing the for loop and printing
each row, and then you are opening a file and only writing the last value that
row was assigned from your for loop. Your for loop that prints is unrelated to
the write operation you then do. `row` had been assigned every value of
`results`, but you only used the last assigned value, once.

What you should do is first open the file, then start your loop, writting
every value of row:

    
    
    with open('test.txt', 'w') as f:
        for row in results:
            print row
            f.write("%s\n" % str(row))
    

If you use the `with` context, it will automatically close the file for you
once you leave that scope. Instead of only converting to a string using `str`
you can use string formatting, and add a newline character.

