How to Use Python to Curl a URL and Save the Output to a File?

9 Replies, 1766 Views

Hey! Your example using `requests` is spot on for python curl url to file. That’s pretty much how I do it too. If you wanna handle errors, you can wrap it in a try-except block like this:

```python
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
with open("output.txt", "wb") as file:
file.write(response.content)
except requests.exceptions.RequestException as e:
print(f"Oops, something went wrong: {e}")
```

This way, it won’t crash if the URL’s down or times out. Also, `raise_for_status()` checks if the request was successful (status code 200).

Messages In This Thread



Users browsing this thread: 1 Guest(s)