【问题标题】:How one can check the size of the file-object without destroying it?如何在不破坏文件对象的情况下检查文件对象的大小?
【发布时间】:2014-09-06 05:38:10
【问题描述】:

我有一个werkzeug.datastructures.FileStorage 类的对象(称为“img”)(这个对象代表一个文件)。我需要将此文件保存在磁盘上。我可以通过以下方式做到这一点:

img.save(fname)

它工作正常。但在我保存文件之前,我需要检查它的大小。我按以下方式进行:

img.seek(0, os.SEEK_END)
size = img.tell()

它也可以正常工作。但问题是我在检查文件大小后无法保存文件。或者,更准确地说,我在磁盘上得到了一个文件,但如果我之前检查过它的大小,它是空的。

如何在不“破坏”文件的情况下检查文件的大小?

【问题讨论】:

  • 如果使用 os.stat 或 os.path.getsize(path) 会怎样?
  • 如果我使用 os.stat(value).st_size 我得到:TypeError: coercing to Unicode: need string or buffer, FileStorage found
  • 默认情况下,文件的“seek head”似乎位于末尾。因此,即使之前没有使用过搜索,也需要搜索文件开头。

标签: python seek werkzeug file-storage


【解决方案1】:

您在保存之前忘记查找文件的开头,因此是空文件

#seek to the end of the file to tell its size
img.seek(0, os.SEEK_END)
size = img.tell()

#seek to its beginning, so you might save it entirely
img.seek(0)    
img.save(fname)

【讨论】:

    【解决方案2】:

    而不是寻找和告诉替换为:

    import os
    img.flush()
    size = os.fstat(img.fileno()).st_size
    

    【讨论】:

      【解决方案3】:

      Werkzeug 的 FileStorage 有一个 content_length 属性:http://werkzeug.pocoo.org/docs/0.10/datastructures/#werkzeug.datastructures.FileStorage.content_length

      img.content_length
      

      【讨论】:

      • 但是,请注意The content-length sent in the header. Usually not available。仅当上传者正确设置了 content-length 标头时,这才有用。
      猜你喜欢
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多