wendu 发表于 2017-5-6 08:20:28

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
amount = app_order
order_no = app_order
deal_time = app_order
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
amount = app_order
order_no = app_order
deal_time = app_order

printuser_id,'|',amount,'|',order_no, '|',deal_time
  再或者 就直接写print然后执行脚本的时候这样执行
  Python test.py > test.txt
  和shell脚本类似
页: [1]
查看完整版本: python脚本相关 连接数据库 重定向