1

I'm trying to make a Python function that lets me input multiple URLs, and it will return multiple dataframes, see below.

def getdata(*urls):
    for i in urls:
        return pd.read_csv(i,skiprows=4)

derby20, derby19, derby18, derby17 = getdata('https://uk-air.defra.gov.uk/data_files/site_data/DESA_2020.csv',
                                             'https://uk-air.defra.gov.uk/data_files/site_data/DESA_2019.csv',
                                             'https://uk-air.defra.gov.uk/data_files/site_data/DESA_2018.csv',
                                             'https://uk-air.defra.gov.uk/data_files/site_data/DESA_2017.csv')

However I get the following error: ValueError: too many values to unpack (expected 4).

Any idea how I can successfully implement this?

Thank you!

Vicrobot
  • 3,795
  • 1
  • 17
  • 31
  • You're returning the result for the first URL, don't return inside the loop if you want all four. – jonrsharpe May 08 '20 at 15:10
  • Please provide a [mcve], as well as the entire error message. Have you tried anything, done any research? See [ask], [help/on-topic]. – AMC May 08 '20 at 17:03
  • Does this answer your question? [How do I return multiple values from a function?](https://stackoverflow.com/questions/354883/how-do-i-return-multiple-values-from-a-function) – AMC May 08 '20 at 17:03

2 Answers2

0

You're returning once and never going in function back again. You can use yield instead of return.

def getdata(*urls):
    for i in urls:
        yield pd.read_csv(i,skiprows=4)

See this:

>>> def foo():
...     for i in range(3): yield i
... 
>>> a, b, c = foo()
>>> a, b, c
(0, 1, 2)
Vicrobot
  • 3,795
  • 1
  • 17
  • 31
0

Change the lines

for i in urls:
    return pd.read_csv(i,skiprows=4)

to

return (pd.read_csv(i, skiprows=4) for i in urls)

because after the first return command your function will not continue, effectively breaking your loop after the first iteration.

MarianD
  • 13,096
  • 12
  • 42
  • 54