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

9 Replies, 1797 Views

If you’re dealing with APIs or need more control, `aiohttp` is great for python curl url to file, especially if you’re into async. Here’s a snippet:

```python
import aiohttp
import asyncio

async def fetch_and_save(url):
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=5) as response:
response.raise_for_status()
with open("output.txt", "wb") as file:
file.write(await response.read())
except Exception as e:
print(f"Error: {e}")

asyncio.run(fetch_and_save("https://example.com"))
```

It’s a bit more complex but super powerful.

Messages In This Thread



Users browsing this thread: 1 Guest(s)