下载文件并覆盖任何具有相同名称的预先存在的文件 - Python 3

时间:2017-03-16 16:05:37

标签: python python-3.x

我目前创建了一个类(子类化线程)我打算用来从url下载文件。我也在使用请求,如果这有所作为。这一切都很好,但我想添加一些功能,但不知道正确的方法。

我会下载的文件很多次(定期)下载以获取最新版本。所以在这种情况下我想:

  1. 使用临时文件名下载文件。

  2. 当我确定已完成文件的完整下载时,覆盖预先存在的文件

  3. 删除临时文件。

  4. 感谢。

    修改:添加了我到目前为止的代码......

    import requests
    import threading
    
    class FileDownload(threading.Thread):
        def __init__(self, url, save_as_name=None, chunk_size=1024):
    
            # Call the constructor from the inherited class
            threading.Thread.__init__(self)
    
            # Class attributes
            self.url = url
            self.save_as_name = save_as_name
            self.chunk_size = chunk_size
            self.file_size = 0
            self.bytes_received = 0
            self.stop_download = False
    
    
        def run(self):
            self._download()
    
    
        def _download(self):
            # If no file save_as_name is provided, use the name of the file
            # from the url
            if self.save_as_name == None:
                self.save_as_name = self.url.split('/')[-1]    
            # Create a Response object
            response = requests.get(self.url, stream=True, timeout=10)
            # Get the size of the file to be downloaded in bytes
            self.file_size = int(response.headers.get('content-length'))
    
            with open(self.save_as_name, 'wb') as file:
                # Write downloaded file contents per iteration
                for chunk in response.iter_content(chunk_size=self.chunk_size):
                    # Mechanism to stop download and therefore its thread
                    if self.stop_download == False:
                        file.write(chunk)
                        # Keep track of the total bytes recieved per iteration
                        self.bytes_received = self.bytes_received + len(chunk)
                    else:
                        break
    

0 个答案:

没有答案