用pymongo在Mongodb的GridFS中保存文件会导致文件被截断-Windows 7上的python 2.7

问题描述 投票:9回答:2

使用pymongo将文件保存在Mongodb的GridFS中会导致文件被截断。

from pymongo import MongoClient
import gridfs
import os

#just to make sure we aren't crazy, check the filesize on disk:
print os.path.getsize( r'owl.jpg' )

#add the file to GridFS, per the pymongo documentation: http://api.mongodb.org/python/current/examples/gridfs.html
db = MongoClient().myDB
fs = gridfs.GridFS( db )
fileID = fs.put( open( r'owl.jpg', 'r')  )
out = fs.get(fileID)
print out.length

在Windows 7上,运行此程序将生成此输出:

145047
864

在Ubuntu上,运行此程序将生成以下(正确)输出:

145047
145047

不幸的是,我正在使用的应用程序以Windows操作系统为目标...

任何帮助将不胜感激!

所以您可以更严格地复制我的示例,'owl.jpg'是从以下位置下载的:http://getintobirds.audubon.org/sites/default/files/photos/wildlife_barn_owl.jpg

python windows mongodb pymongo gridfs
2个回答
10
投票

嘿,改变中

fileID = fs.put( open( r'owl.jpg', 'r')  )

至:

fileID = fs.put( open( r'owl.jpg', 'rb')  )

修复了Windows 7上程序的行为。可惜,行为在操作系统之间是不同的...


5
投票

您已经有了答案,但出于好奇:

http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

在Windows上,附加到模式的'b'以二进制模式打开文件,因此也有'rb','wb'和'r + b'之类的模式。 Windows上的Python区分文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动更改。对文件数据进行这种幕后修改对于ASCII文本文件来说是很好的选择,但它会破坏二进制数据,例如JPEG或EXE文件中的二进制数据。读写此类文件时,请务必小心使用二进制模式。

© www.soinside.com 2019 - 2024. All rights reserved.