2015-09-01 130 views
0

我已经将一些PDF,PNG文件上传到本地mongodb实例。我错误地删除了这些文件,并且无法使用常规恢复选项来恢复它们。但是,它们在我本地的mongodb数据库中。我如何在计算机上将它们保存为原始格式?使用Python保存存储在Mongodb GridFS中的pdf文件

我了解以下内容:

import pymongo as pym 
import gridfs 

def connectToDb(): 
    client = pym.MongoClient('mongodb://localhost:27017/') 
    db = client.questionbank 
    collectn = db.questionbank 
    fs = gridfs.GridFS(db) 
    return db, collectn, fs 

db, collectn, fs = connectToDb() 

filelist = list(db.fs.files.find({}, {"_id": 1, "filename": 1})) 
fileid = filelist[0]['_id'] 
fobj = fs.get(fileid) 

## I don't know what to do after this. I think I cannot use read since I don't 
## want the string. I want to save the pdf file as a pdf file. 

任何帮助将不胜感激。提前致谢。

回答

0

好吧,我想出了我自己的想法。它可以通过以下方式进行:

要将上面的代码中添加行:

f = open('tempfigfile.pdf', 'wb') 
f.write(fobj.read()) 
f.close() 

这将文件保存为tempfigfile.pdf。

0

此代码将所有文件从mongodb gridfs保存到你的本地文件夹。

i=0 
cursor=fs.find() 
while(i < cursor.count()): 
    fi=cursor.next() 
    with open("C:\\localfolder\\"+fi.filename,"wb") as f: 
     f.write(fi.read()) 
     f.closed 
     i=i+1 
相关问题