7月 08

python mongodb 变量做集合(collection)名

【2011-7-8 张子萌】
当前需求:1)将某个目录下的html文件插入到mongo数据库中。
2)cellection名为html页的上级目录名。
3)document为文件名、html内容

测试目录位置/home/test

#!/usr/bin/python
#-*- coding:utf-8 -*-
import re
import os
import pymongo

find_file=re.compile(r”.html$”)
find_path=r”/home/test”
find_walk=os.walk(find_path)
conn = pymongo.Connection(“localhost”,27017)
db = conn.mytest
for path,dirs,files in find_walk:
for file in files:
if find_file.search(file):
collection_name=path.split(“/”)[2]
get_html=open(path+”/”+file,’r’)
exec(‘db.’+collection_name+’.save({“file_name”:file,”context”:get_html.read()})’)
get_html.close()

遇到一个问题,好像collection如只是数字(int)插入有问题,所以如果用数字名做collection名可以在前面加个字母。