> ## Content Index
> Fetch the complete content index at: https://datascientyst.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# How to Read CSV Directly from a URL in Pandas and Requests
- URL: https://datascientyst.com/how-to-read-csv-directly-from-a-url-in-pandas-and-requests/
- Published: 2025-04-14T13:11:32.000Z
- Updated: 2025-04-14T13:11:32.000Z
- Author: John D K
- Tags: Create, read_csv()

Pandas can read CSV files directly from a URL by passing the URL to the `read_csv()` method. This is useful when working with datasets hosted online and for ad hoc tests.

We can use the following syntax to **read CSV from URL in Pandas**:

**(1) Margin only on rows**

```python
import pandas as pd
url = "https://raw.githubusercontent.com/softhints/Pandas-Exercises-Projects/refs/heads/main/data/europe_pop.csv"
df = pd.read_csv(url)

```

## Basic Usage

You can use `pd.read_csv()` with a URL just like you would with a local file:

```python
import pandas as pd
url = "https://raw.githubusercontent.com/softhints/Pandas-Exercises-Projects/refs/heads/main/data/europe_pop.csv"
df = pd.read_csv(url)

```

This will download and read the CSV file into a DataFrame.

## Notes

- The URL must point directly to a `.csv` file
- Works with:  
  - `http`
  - `https`
  - `ftp`
- If the CSV is encoded differently (e.g. UTF-16), you can specify it as param:

```python
df = pd.read_csv(url, encoding='utf-16')

```

## Read Data with Requests

In some cases you may need to use Python library requests to read the data first and then load it as DataFrame. This could be related to authentication or security. In this case we can use the following code to read the data:

```python
import pandas as pd
import io
import requests

url = "https://raw.githubusercontent.com/softhints/Pandas-Exercises-Projects/refs/heads/main/data/europe_pop.csv"

content = requests.get(url).content
df = pd.read_csv(io.StringIO(content.decode('utf-8')))
df

```

This approach is ideal for:

- quick prototyping
- accessing public datasets
- integration with APIs or
- GitHub-hosted data.

### Further Reading

- [Convert text data from requests object to dataframe with pandas](https://stackoverflow.com/questions/39213597/convert-text-data-from-requests-object-to-dataframe-with-pandas?ref=datascientyst.com)
- [Pandas read\_csv from url](https://stackoverflow.com/questions/32400867/pandas-read-csv-from-url?ref=datascientyst.com)
- [Pandas read\_csv documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read%5Fcsv.html?ref=datascientyst.com)
- [Example datasets hosted on GitHub](https://github.com/awesomedata/awesome-public-datasets?ref=datascientyst.com)