Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7.11 write output to a text file

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

like image 766
SafetyNetter Avatar asked Dec 06 '25 10:12

SafetyNetter


2 Answers

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)

like image 140
ode2k Avatar answered Dec 08 '25 09:12

ode2k


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))
like image 45
DevShark Avatar answered Dec 08 '25 10:12

DevShark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!