背景:

因测试性能,需要把mysql的数据导出到mongodb中。


前提:

1、用navicat或者别的什么mysql客户端先把mysql的数据表导出成json格式,本人用的是navicat。

2、利用mongodb的mongoimport工具。


代码:

#coding=utf-8
import os
import json
import subprocess


if __name__ == "__main__":
listfile=os.listdir('.')
for file in listfile:
print '处理:'+file
des_file = "d:/out/"+file
tmp = "d:/out2/"+file
without_suffix = file.split('.')[0]
suffix = file.split('.')[-1]
if suffix == 'py':
continue
in_f = open(file, 'r')
out_f = open(des_file, 'w')
# navicat 导出的格式有点点不大合适,需要把{recoder:[{item1},{item2}]}改成:[{item1},{item2}]格式
for index, line in enumerate(in_f.readlines()):
if index == 0:
out_f.write('[\n')
continue
if '"RECORDS":[' in line:
continue
else:
out_f.write(line)
in_f.close()
out_f.close()

# 删除最后一行
with open(des_file) as f:
lines = f.readlines()
curr = lines[:-1]

f = open(tmp, 'w')
f.writelines(curr)
f.close()

# 执行mongodb import命令
# -d 数据库名 -c 数据表名 -f JSON文件
cmd ='D:\MongoDB\bin\mongoimport -d"chanzai_dev" -c"%s" --jsonArray --type=json --file=D:\out2\%s.json' % (without_suffix, without_suffix)
print cmd
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)


更多相关文章

  1. Python MOOC简单获取网页内容并以html格式保存在本地
  2. Python数据格式化
  3. Django i18n:为{% blocktrans %}块推荐的大小和格式?
  4. Linux 的磁盘格式化、挂载、磁盘检验、df、du、fdisk、free命令
  5. 常见压缩格式的区别,及 Linux 下的压缩相关指令
  6. linux 下常用音频格式的转化
  7. 如何使用ffmpeg将m4v和wmv视频转换为mp4格式?
  8. Linux第三章 命令基本格式及文件处理命令
  9. 是否遇到过MySQL workbench text字段不能直接放入json格式内容

随机推荐

  1. 检索InnoDB组合密钥表的最后插入ID
  2. php 实现下载的方法
  3. 大文件从指定行开始读取
  4. 如何通过热门/上升的帖子订购
  5. mysql_query会自动执行,但不会在onClick时
  6. php写app接口并返回json数据
  7. PHP环境搭建和编写API接口
  8. ajax php bomt头 utf-8带来的奇怪问题。
  9. MySQL错误1046:未选择数据库
  10. PHP 开发环境配置