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()方法。
博客介绍了Python文件读写时可能出错导致后续操作无法调用的问题。为保证无论是否出错都能正确关闭文件,可使用特定方式实现,同时提到Python引入语句来自动调用方法,使代码更简洁,无需手动调用相关方法。
696

被折叠的 条评论
为什么被折叠?



