简体   繁体   English

如何限制 python 中下载的文件大小?

[英]how can I limit downloaded file size in python?

I am trying to limit downloaded file size to only < 1MB files, but my code is somehow buggy because it downloads > 1MB, however, when I tried to test it downloads more than 1mb file我试图将下载的文件大小限制为仅 < 1MB 的文件,但我的代码存在某种错误,因为它下载 > 1MB,但是,当我尝试测试它时下载超过 1mb 的文件

self.url = 'https://www.google.com/search?q=filetype:{}+{}&num={}'.format(self.ext, self.magic_header, self.max)
self.MAX_SIZE = 1000000 # 1024 * 1024 this doesnt work either
try:
            response = requests.head(href)
            total = response.headers.get('content-length')
            if int(total) > self.MAX_SIZE:
              print "maximum size (%d kbs)" % (self.MAX_SIZE/1024)
            else:
              if total is None:
                pass
              else:
                #if os.path.exists(OUTPUT_DIR):
                #  print("Deleting old output directory")
                #  shutil.rmtree(OUTPUT_DIR)
                #print("Creating output directory")
                #os.mkdir(OUTPUT_DIR)
                os.system('wget -P %s %s'%(OUTPUT_DIR, href))
          except Exception as e:
            pass```

output output

204K 'NetLogo Tutorial 1 in Spanish.pdf'  1.2M  zElquehacertutorial.pdf
916K  proceso_tutorial_de_la_mcdst.pdf    2.3M  z-El-sistema-tutorial-en-la-UV.pdf

if you have the file object, you can use this如果你有 object 文件,你可以使用这个

import os
os.fstat(f.fileno()).st_size > self.MAX_SIZE:

os.fstat(f.fileno()).st_size will give the file's size in byte os.fstat(f.fileno()).st_size 将以字节为单位给出文件的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM