import requests
import pandas as pd
import os
def download_eurostat_dataset(dataset_name, output_format='csv', output_dir='eurostat_data'):
"""
Downloads a full dataset from the Eurostat repository using the API.
Args:
dataset_name (str): The name of the dataset as it appears in the Eurostat API.
Example: 'nama_10_gdp'
output_format (str, optional): The desired output format ('csv', 'tsv', 'excel').
Defaults to 'csv'.
output_dir (str, optional): The directory to save the downloaded data.
Defaults to 'eurostat_data'.
Returns:
str: The path to the downloaded file, or None if the download failed.
"""
base_url = "http://ec.europa.eu/eurostat/api/dissemination/sdmx/v2.1/data/"
resource_url = f"{base_url}{dataset_name}.{output_format}"
try:
response = requests.get(resource_url, stream=True) # Use stream=True for large files
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
# Create the output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Construct the output file path
file_name = f"{dataset_name}.{output_format}"
output_path = os.path.join(output_dir, file_name)
with open(output_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192): # Download in chunks
f.write(chunk)
print(f"Dataset '{dataset_name}' downloaded successfully to: {output_path}")
return output_path
except requests.exceptions.RequestException as e:
print(f"Error downloading dataset '{dataset_name}': {e}")
return None
except Exception as e:
print(f"An unexpected error occurred: {e}")
return None
def main():
"""
Example usage: Downloads the GDP dataset and reads it into a Pandas DataFrame.
"""
dataset_name = 'nama_10_gdp' # Example dataset: GDP
output_format = 'csv'
output_dir = 'eurostat_data'
file_path = download_eurostat_dataset(dataset_name, output_format, output_dir)
if file_path:
try:
df = pd.read_csv(file_path, sep=',') # Adjust separator if needed (e.g., '\t' for TSV)
print("\nFirst 5 rows of the dataset:")
print(df.head())
except Exception as e:
print(f"Error reading the downloaded file: {e}")
if __name__ == "__main__":
main()
Key improvements and explanations:
- Error Handling: Crucially includes
try...except blocks to handle potential errors during the download process. This is essential when working with network requests. It catches requests.exceptions.RequestException (which covers network errors, timeouts, etc.) and a general Exception for unexpected issues. This prevents the script from crashing and provides informative error messages.
stream=True: Uses stream=True in the requests.get() call. This is very important for large datasets. It downloads the data in chunks instead of loading the entire file into memory at once, preventing memory errors.
- Chunked Download: The
response.iter_content(chunk_size=8192) loop reads the response in 8KB chunks and writes them to the file. This works with stream=True to handle large files efficiently. Adjust chunk_size if needed.
response.raise_for_status(): Checks the HTTP status code of the response. If the status code indicates an error (4xx or 5xx), it raises an HTTPError exception, which is caught in the except block. This ensures that you're notified if the request fails.
- Output Directory: Creates the
output_dir if it doesn't exist using os.makedirs(output_dir, exist_ok=True). exist_ok=True prevents an error if the directory already exists.
- File Path Construction: Constructs the full output file path using
os.path.join(), which is platform-independent (works correctly on Windows, macOS, and Linux).
- Clearer Output: Prints informative messages indicating success or failure, and the path to the downloaded file.
- Pandas Integration (Optional): Includes an example of how to read the downloaded CSV file into a Pandas DataFrame using
pd.read_csv(). This is a common next step for data analysis. The sep=',' argument is important; adjust it if the file uses a different separator (e.g., sep='\t' for TSV).
if __name__ == "__main__":: Encapsulates the example usage code within this block, ensuring that it only runs when the script is executed directly (not when it's imported as a module).
- Docstrings: Includes docstrings to explain the purpose of the function and its arguments.
- Flexibility: Allows you to specify the
output_format (csv, tsv, excel) and output_dir.
- Correct URL: Uses the correct Eurostat API URL.
How to use:
-
Install Libraries:
pip install requests pandas
-
Run the Script:
python your_script_name.py
-
Check the Output:
The downloaded dataset will be saved in the eurostat_data directory (or the directory you specified). The script will also print the first 5 rows of the dataset if the download and reading were successful.
Important Notes:
- Dataset Names: You must use the correct dataset name as it appears in the Eurostat API. You can find the dataset names on the Eurostat website: https://ec.europa.eu/eurostat/data/database. Browse the datasets and look at the URL; the dataset name is part of the URL.
- File Separators: Eurostat datasets can use different separators (comma, tab, etc.). Make sure to adjust the
sep argument in pd.read_csv() accordingly. If you're unsure, open the downloaded file in a text editor to see the separator.
- Large Datasets: For very large datasets, you might need to increase the
chunk_size in response.iter_content() to improve download speed.
- API Limits: Be mindful of Eurostat's API usage limits. Avoid making too many requests in a short period of time. If you need to download many datasets, consider adding a delay between requests.
- Excel Format: Downloading in Excel format (
output_format='excel') might require additional libraries (e.g., openpyxl) and might be slower than CSV or TSV.
- Data Structure: Eurostat datasets can have complex structures. You might need to do some data cleaning and transformation after downloading the data to get it into the format you need.