Python: Download CSV file, check return code?
Question: I am downloading multiple CSV files from a website using Python. I would like
to be able to check the response code on each request.

I know how to download the file using `wget`, but not how to check the
response code:

    
    
    os.system('wget http://example.com/test.csv')
    

I've seen a lot of people suggesting using requests, but I'm not sure that's
quite right for my use case of saving CSV files.

    
    
    r = request.get('http://example.com/test.csv')
    r.status_code # 200
    # Pipe response into a CSV file... hm, seems messy?
    

What's the neatest way to do this?


Answer: You can use the `stream` argument - along with `iter_content()` it's possible
to stream the response contents right into a file ([docs](http://docs.python-
requests.org/en/latest/user/advanced/#body-content-workflow)):

    
    
    import requests
    
    r = None
    try:
        r = requests.get('http://example.com/test.csv', stream=True)
        with open('test.csv', 'w') as f:
            for data in r.iter_content():
                f.write(data)
    
    finally:
        if r is not None:
            r.close()
    

