import pymongo
import bson.binary
from cStringIO import StringIO
def lead_in_Mongodb(filename_lst, id_lst, url_lst):
client = pymongo.MongoClient()
db = client.Spyder
collection = db['QuestMobile']
fs = GridFS(db, collection="QuestMobile")
for i in range(len(filename_lst)):
with open(id_lst[i]+'.pdf', 'rb') as f:
content = StringIO(f.read())
collection.save(dict(
content=bson.binary.Binary(content.getvalue()),
filename=filename_lst[i],
url_id = id_lst[i],
url = url_lst[i]
))
with
由于文件读写时都有可能产生IOError
,一旦出错,后面的f.close()
就不会调用。所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用try ... finally
来实现:
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
但是每次都这么写实在太繁琐,所以,Python引入了with
语句来自动帮我们调用close()
方法:
with open('/path/to/file', 'r') as f:
print(f.read())
这和前面的try ... finally
是一样的,但是代码更佳简洁,并且不必调用f.close()
方法。