Home >Backend Development >Python Tutorial >How to Read CSV from URL in Pandas: Why am I getting the error \'Expected file path name or file-like object, got type\'?

How to Read CSV from URL in Pandas: Why am I getting the error \'Expected file path name or file-like object, got type\'?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 09:37:03283browse

How to Read CSV from URL in Pandas:  Why am I getting the error

Pandas: Reading CSV from URL

Problem:

Encountering an error while attempting to read a CSV file from a given URL using Python 3.x: "Expected file path name or file-like object, got type."

Error Resolution:

The error arises because Python 3.4 requires the use of StringIO to handle the byte-like string returned by the requests.get() method in pandas.read_csv().

Fix:

To fix this issue, convert the byte-like string into a file-like object using StringIO, as demonstrated below:

<code class="python">import io
import pandas as pd
import requests

url = "https://github.com/cs109/2014_data/blob/master/countries.csv"

# Get the CSV data from the URL
response = requests.get(url)

# Convert the byte-like string to a StringIO object
csv_string = io.StringIO(response.content.decode('utf-8'))

# Read the CSV data into a DataFrame
df = pd.read_csv(csv_string)</code>

By using StringIO, the byte-like string is interpreted as a file-like object, allowing pandas.read_csv() to read the CSV data successfully.

The above is the detailed content of How to Read CSV from URL in Pandas: Why am I getting the error 'Expected file path name or file-like object, got type'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn