【问题标题】:Python: Print standard output to multiple files after a set number of rowsPython:在设定的行数后将标准输出打印到多个文件
【发布时间】:2013-12-04 19:41:23
【问题描述】:

我有一个包含 7000 万条记录的数据库表和另一个包含 900 万条记录的表。我试图让我的程序在循环达到 1,000,000 条记录后将连接的表打印到多个文件中,并继续这样做,直到整个查询转储完成。提供的是我的代码:

from netaddr import *
import sys, csv, sqlite3, logging, time, os, errno

# Functions
s = time.strftime('%Y%m%d%H%M%S')

# Create file from standard output for database import
class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open((s) + "_" + sys.argv[1], "a")

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

def ExportVNEDeltas():
    sys.stdout = Logger() # Start screen capture to log file

    con = sqlite3.connect(sys.argv[1])
    cur = con.cursor()

    try:
        cur.execute('SELECT tbl70m.IP, tbl9m.ip, tbl0m.Cgroup, \
            TOTAL(case when tbl9m.vne = "internal" then 1 end), \
            TOTAL(case when tbl9m.vne = "external" then 1 end), \
            TOTAL(case when tbl9m.vne = "enterprise" then 1 end), \
            TOTAL(case when tbl9m.vne = "zone" then 1 end) \
            FROM tbl70m LEFT OUTER JOIN tbl9m ON tbl70m.IP=tbl9m.ip \
            GROUP BY tbl70m.IP \
            ORDER BY tbl70m.Cgroup, tbl70m.IP;')

        data = cur.fetchall()

        for row in data:
            print '"'+str(row[0])+'","'+str(row[1])+'","'+str(row[2])+'","'+str(row[3])+'","'+str(row[4])+'","'+str(row[5])+'","'+str(row[6])+'"'

    except (KeyboardInterrupt, SystemExit):
        raise

    con.close()
    sys.stdout = sys.__stdout__ # stops capturing data from database export.

# Primary function to execute
def main():
    ExportVNEDeltas()

if __name__=='__main__':
    main()

一旦达到 1,000,000 条记录并创建一个新文件,我似乎无法弄清楚如何停止打印标准输出。我需要硬停止 1,000,000 的原因是我们可以在 Microsoft Excel 中查看这些数据。

【问题讨论】:

    标签: python sql export-to-csv


    【解决方案1】:

    您可以将此规则添加到您的Logger:

    class Logger(object):
        def __init__(self, maxlines=1000000):
            self.maxlines = maxlines
            self.lines = 0
            self.terminal = sys.stdout
            self.log = open((s) + "_" + sys.argv[1], "a")
    
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
            self.lines += 1
            if self.lines == self.maxlines:
                self.log.close()
                self.log = open(...)
                self.lines = 0
    

    【讨论】:

    • 试过了,仍然将所有 7000 万条记录打印到一个文件中。看起来它在我的 FOR 循环中。我一直在考虑将 OFFSET 添加到我的查询中,但不确定信息是否会重复。有什么想法吗?
    • 您要更改文件名吗?您当前的代码只设置一次s
    • 我尝试在您建议的 open(...) 行中添加一个唯一名称,但数据只是一直写入原始 open((s) + "_" sys.argv[ 1] 字符串。
    • 那我就难过了,对不起!
    猜你喜欢
    • 2013-05-01
    • 2016-06-26
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多