Ask Your Question
4

How can a csv file be downloaded using requests for a url?

asked 2022-03-08 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-07-21 05:00:00 +0000

pufferfish gravatar image

Here is an example code snippet to download a CSV file using requests library in Python:

import requests

url = "https://example.com/my_file.csv"  # Replace with your URL
filename = "my_download.csv"  # Replace with desired file name

response = requests.get(url)

if response.status_code == 200:
    with open(filename, "wb") as f:
        f.write(response.content)
    print("File downloaded successfully.")
else:
    print("Download unsuccessful with status code:", response.status_code)

In the above code, we first define the url of the CSV file to be downloaded and the desired filename for the downloaded file.

We then make a GET request to the URL using requests.get() method and store the response in a variable response. The response.content contains the bytes of the downloaded file.

We then check if the request was successful with a status code of 200. If yes, we open a file with the desired filename in binary write mode ("wb") and write the content of the response to the file. We then print a success message.

If the request was unsuccessful, we simply print an error message with the status code.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-08 11:00:00 +0000

Seen: 10 times

Last updated: Jul 21 '22