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名可以在前面加个字母。

5月 08

python查找目录下指定文件

[张子萌 2011-05]
导入os模块使用walk函数。walk函数比较简单,迭代返回元组,一个元组有三个元
素(遍历的路径、当前遍历路径下的目录、当前遍历目录下的文件名)。

建立一个textfind目录。建立目录1,目录1下有目录2和文件1.txt,在目录2下有
3目录、33目录和2.txt,在目录3下有3.txt。
测试结果:
>>> import os
>>> a=os.walk(r’testfind/’)
>>> for i in a:
… print i

(‘testfind/’, [‘1’], [])
(‘testfind/1’, [‘2’], [‘1.txt’])
(‘testfind/1/2’, [‘3′, ’33’], [‘2.txt’])
(‘testfind/1/2/3’, [], [‘3.txt’])
(‘testfind/1/2/33’, [], [])

偷懒的方法用命令find比较简单。使用python如果要找指定文件,还需要用正则匹
配一下。

import re
import os
find_file=re.compile(r”.txt$”)
find_path=r”./testfind”
find_walk=os.walk(find_path)
for path,dirs,files in find_walk:
for file in files:
if find_file.search(file):
print(“%s”%path+”/”+file)