使用pymongo在Mongodb的GridFS中保存一个文件会导致截短的文件-Windows 7上的python 2.7

2024-05-18 21:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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下载的


Tags: 文件thetoorgimporthttposowl
2条回答

你已经得到了答案,但是出于好奇:

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

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

嘿,换衣服

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

致:

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

修复了Windows 7上程序的行为。太糟糕了操作系统之间的行为不同。。。

相关问题 更多 >

    热门问题