将SQLALCHEMY中的数据输出到file.txt中

时间:2015-08-07 22:35:13

标签: python-2.7 file-io sqlalchemy

我正在尝试打印数据,如下所示,并将其导出到文本文件中。我有与这些实例化对象相对应的表。

#ASSESSMENT 
    api = BaseAPI()

    assessment1 = api.create_assessment('Situation Awareness', 'Developing better skills',u2, v3, category=[l,dm,tc,sa], element=[sa1,sa2,sa3,dm1,dm2,dm3,ct1,ct2,ct3,l1,l2,l3])

    assessment2 = api.create_assessment('Decision-Making', 'better decisions', u1, v2, category=[l,dm,tc,sa], element=[sa1,sa2,sa3,dm1,dm2,dm3,ct1,ct2,ct3,l1,l2,l3])

    assessment3 = api.create_assessment('Leadership', 'defining new leaders',u3, v1, category=[l,dm,tc,sa], element=[sa1,sa2,sa3,dm1,dm2,dm3,ct1,ct2,ct3,l1,l2,l3])

我使用的查询方法是:

    import sys

    class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger('DataOutput.txt')

def analystview(object):
    for a in self.session.query(Assessment).\
    filter(Assessment.user_id==Assessment.user_id).\
    filter(Assessment.name == Assessment.name).all():
        for a in assessments:
            print(a.name, a.text, a.user_id)

api = BaseAPI()
analystview(api)

我在上面的代码中做错了什么,它不是从我的查询打印输出?

1 个答案:

答案 0 :(得分:0)

此格式有效!尽管如此,输出过程是否有更好的方法?我的意思是,一种更简洁的方法来输出查询到文本文件?

#!/usr/bin/env python


import sys
import sqlite3

db = sqlite3.connect('some.db') # used sqlite3 to go through results/data
cur = db.cursor()
query = ("SELECT * FROM users")
lines = cur.execute(query)
data = cur.fetchall()


class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger('DataOutput.txt') #name of the text file
print(data) #has to be after the sys.stdout to print out results