Himanshu Doneria
Himanshu Doneria

Reputation: 57

TypeError: expected string or bytes-like object in Python

I am currently breaking on the subjected break. What is this TypeError, and how do I resolve it? What are the necessary amendments required in the code?

from urllib.request import urlretrieve

stoxxeu600_url = urllib.request.urlretrieve('https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt')
vstoxx_url = urllib.request.urlretrieve('https://www.stoxx.com/document/Indices/Current/HistoricalData/h_vstoxx.txt')

data_folder = 'data/' #Save file to local target destination.
stoxxeu600_filepath = data_folder + "stoxxeu600.txt"
vstoxx_filepath = data_folder + "vstoxx.txt"
urlretrieve(stoxxeu600_url,stoxxeu600_filepath)

This is the output:

File "/home/aryabhatta/anaconda3/lib/python3.6/urllib/parse.py", line 938, in splittype
match = _typeprog.match(url)

TypeError: expected string or bytes-like object

Upvotes: 0

Views: 6253

Answers (2)

Xnkr
Xnkr

Reputation: 562

You can see from the documentation of urlretrieve() that the method returns a tuple (filename, headers)

In your code, you first call urlretrieve() and store it into stoxxeu600_url

stoxxeu600_url = urllib.request.urlretrieve('https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt')

stoxxeu600_url now has (filename, headers) returned by urlretrieve()

You then call urlretrieve() again with stoxxeu600_url which is a tuple, and not the str/byte object, that the method expects. Thereby, causing the TypeError.

urlretrieve(stoxxeu600_url,stoxxeu600_filepath)

To fix it, just set stoxxeu600_url to the url and then call the method.

from urllib.request import urlretrieve

stoxxeu600_url = 'https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt'
stoxxeu600_filepath = "stoxxeu600.txt"
urlretrieve(stoxxeu600_url, filename=stoxxeu600_filepath)

Upvotes: 1

Rob Bricheno
Rob Bricheno

Reputation: 4653

urlretrieve wants a string as its first argument. So stoxxeu600_url should be a string.

from urllib.request import urlretrieve

stoxxeu600_url = 'https://www.stoxx.com/document/Indices/Current/HistoricalData/hbrbcpe.txt'
data_folder = 'data/' #Save file to local target destination.
stoxxeu600_filepath = data_folder + "stoxxeu600.txt"
urlretrieve(stoxxeu600_url, stoxxeu600_filepath)

Upvotes: 0

Related Questions