Python open FTP url and write to file
Question: How can I open and FTP url and download it into a file. What I'm trying looks
something like this:

    
    
    from contextlib import closing
    from urllib.request import urlopen
    
    url = 'ftp://whatever.com/file.txt'
    target_path = 'file.txt'
    
    with closing(urlopen(url)) as source:
        with open(target_path, 'wb') as target:
            target.write(source)
    

However, this fails with the following error:

    
    
    TypeError: 'addinfourl' does not support the buffer interface
    

Is there any simple way to make this work? Especially if I want to extend it,
so that the file is extracted while it is downloaded?


Answer: The `write` requires object with buffer interface in particular `bytes`, but
the `source` is actually `BufferedReader` (or `HTTPResonse` if http). To get
bytes you need to call
[`BufferedReader.read()`](https://docs.python.org/3/library/io.html#io.BufferedReader.read)

    
    
    from contextlib import closing
    from urllib.request import urlopen
    
    url = 'ftp://whatever.com/file.txt'
    target_path = 'file.txt'
    
    with closing(urlopen(url)) as source:
        with open(target_path, 'wb') as target:
            target.write(source.read())
    

