Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How one can check the size of the file-object without destroying it?

I have an object (called "img") of the werkzeug.datastructures.FileStorage class (this object represents a file). I need to save this file on the disk. I can do it in the following way:

img.save(fname)

It works fine. But before I save the file, I need to check its size. I do it in the following way:

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

It works also fine. But the problem is that I cannot save the file after I check its size. Or, more precisely, I get a file on the disk but it is empty, if I checked its size before.

How can I check the size of the file without "destroying" it?

like image 508
Roman Avatar asked Feb 12 '23 02:02

Roman


1 Answers

you forgot to seek the file to its beginning before saving it, hence the empty file

#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)
like image 139
sebdelsol Avatar answered Feb 16 '23 04:02

sebdelsol