【问题标题】:Saving a file in Mongodb's GridFS with pymongo results in a truncated file - python 2.7 on Windows 7使用 pymongo 在 Mongodb 的 GridFS 中保存文件会导致文件被截断 - Windows 7 上的 python 2.7
【发布时间】:2013-12-31 08:12:58
【问题描述】:

使用 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


    【解决方案1】:

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

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

    在 Windows 上,附加到模式的 'b' 以二进制模式打开文件,因此还有 'rb'、'wb' 和 'r+b' 等模式。 Windows 上的 Python 区分文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动稍作更改。这种对文件数据的幕后修改适用于 ASCII 文本文件,但它会破坏 JPEG 或 EXE 文件中的二进制数据。读写此类文件时要非常小心使用二进制模式。

    【讨论】:

      【解决方案2】:

      呵呵,变态

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

      到:

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

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

      【讨论】:

      • 即使在 Linux 上,我也必须使用 'rb' 打开文件,否则我会收到“'str' does not support buffer interface”错误
      • python 3 要求文件以二进制模式打开,否则会出现 utf 解码错误(或其他系统默认字符串解码器)
      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2014-05-11
      • 2013-10-27
      相关资源
      最近更新 更多