python脚本相关 连接数据库 重定向

今天写了一个 脚本 作用是将一个数据库中的一个查询结果 跑出来 放到一个文件中 查询结果有70k多条。

涉及到了 2个知识点吧 记录一下

1 连mysql的问题 主要是这个MySQLdb模块儿  http://www.cnblogs.com/czh-liyu/archive/2008/04/13/1151758.html  主要可以参考这个url

 

2 结果重定向的问题

   就是平时在控制台打出的结果 打到一个文件中去 可以这样做  

def print_result(cursor, list):
    '''打印出查询结果'''
    f = open('test.txt','w')
    total = 0
    for app_order in list:
        user_id = app_order[0]
        amount = app_order[1]
        order_no = app_order[2]
        deal_time = app_order[3]
 
        print >> f, user_id,'|',amount,'|',order_no, '|',deal_time

 或者 这样

 

import sys
def print_result(cursor, list):
    '''打印出查询结果'''
    
    sys.stdout=open('test.txt','w')
    total = 0
    for app_order in list:
        user_id = app_order[0]
        amount = app_order[1]
        order_no = app_order[2]
        deal_time = app_order[3]
 
 
        print  user_id,'|',amount,'|',order_no, '|',deal_time

 

再或者 就直接写print然后执行脚本的时候这样执行

 Python test.py > test.txt

和shell脚本类似

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值