β

Python操作

田加国 | 전가국 | GUOGUO 87 阅读

操作json

dump和dumps的区别是dump会生成一个类文件对象,dumps会生成字符串load和loads区别是load解析类文件对象,loads解析字符串格式的JSON

把json object的value由字符串改为[],load与loads,dump与dumps的区别

import json
def changejson(jstr):
  sdict = json.loads(jstr)
  # print sdict
  rdict = {}
  for k in sdict:
    item = []
    item.append(sdict[k])
    rdict[k] = item
  rjson = json.dumps(rdict)
  return rjson
print changejson('{}')

操作文件

# example 1:
t_file=open("/xxxx/xxx.txt", "r")
while 1:
  sline = t_file.readline().strip('\n')
  if not sline:
    break
  print "The Line is: %s" % (sline)
t_file.close()
# example 2:
# split file and hash with one filed
def splitfile(sfile, index, pre):
  f=open(sfile)
  files=[]
  for i in range(0, 64):
    files.append(open("/tmp/tmp/%s_%s" % (pre, i), "w"))
  while 1:
    line = f.readline().strip('\n')
    if not line:
      break
    row = line.split('\t')
    tid = row[index]
    htid = hash(tid)
    if (htid <= 0):
      htid = 0 - htid
    files[htid % 64].write("%s\n" %  (line))
  f.close()
  for i in range(0, 64):
    files[i].close()
#f_split("/tmp/tmp/jiaguo20150108_cpalog.dat", 1, "detail")

操作数据库

安装数据连接池模块DBUtils

# tar zxvf DBUtils-0.9.4.tar.gz

# cd DBUtils-0.9.4/

# python setup.py install

编写python脚本 Test.py

#!/usr/bin/python
import MySQLdb
from DBUtils.PooledDB import PooledDB
# 创建连接池
dbpool = PooledDB(creator = MySQLdb, maxusage=100, host="localhost",user="user",passwd="passwd",db="db",port=3306, charset="utf8")
# 使用
def findFromDb(sql):
  try:
    conn = dbpool.connection()
    cur = conn.cursor()
    count = cur.execute(sql)
    if (count > 0):
      # results = cur.fetchall()
      # for result in results:
        # ......
    cor.close()
    conn.close()
  except MySQLdb.Error,e:
    print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    result = {}
    return result
print findFromDb("......")
作者:田加国 | 전가국 | GUOGUO
从一到正无穷
原文地址:Python操作, 感谢原作者分享。