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

Rom*_*man 4 python werkzeug file-storage seek

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

img.save(fname)
Run Code Online (Sandbox Code Playgroud)

它工作正常。但是在我保存文件之前,我需要检查它的大小。我通过以下方式做到这一点:

img.seek(0, os.SEEK_END)
size = img.tell()
Run Code Online (Sandbox Code Playgroud)

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

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

seb*_*sol 6

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

#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)
Run Code Online (Sandbox Code Playgroud)