2015-09-01 127 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 
相關問題