There are multiple ways to get CSV data from URLs. From your example, namely Yahoo Finance, you can copy the Historical data link and call it in Pandas

...
HISTORICAL_URL = "https://query1.finance.yahoo.com/v7/finance/download/GOOG?period1=1582781719&period2=1614404119&interval=1d&events=history&includeAdjustedClose=true"

df = pd.read_csv(HISTORICAL_URL)

A general pattern could involve tools like requests or httpx to make a GET|POST request and then get the contents to io.

import pandas as pd
import requests
import io

url = 'https://query1.finance.yahoo.com/v7/finance/download/GOOG'
params ={'period1':1538761929,
         'period2':1541443929,
         'interval':'1d',
         'events':'history',
         'crumb':'v4z6ZpmoP98',
        }

r = requests.post(url,data=params)
if r.ok:
    data = r.content.decode('utf8')
    df = pd.read_csv(io.StringIO(data))

To get the params, I just followed the liked and copied everything after ‘?’. Check that they match ;)

Results:

Update:


If you can see the raw csv contents directly in url, just pass the url in pd.read_csv Example data directly from url:

data_url ='https://raw.githubusercontent.com/pandas-dev/pandas/master/pandas/tests/data/iris.csv'

df = pd.read_csv(data_url)
Answer from Prayson W. Daniel on Stack Overflow
🌐
Saturn Cloud
saturncloud.io › blog › downloading-a-csv-from-a-url-and-converting-it-to-a-dataframe-using-python-pandas
Downloading a CSV from a URL and Converting it to a DataFrame using Python Pandas | Saturn Cloud Blog
May 1, 2026 - In this guide, we covered the process of downloading a CSV file from a URL and converting it into a Pandas DataFrame using Python. We discussed the pros and cons of this method, common errors, and provided detailed examples for handling potential issues.
Discussions

pandas - Saving a downloaded CSV file using Python - Stack Overflow
I want to download a csv file from a link with request and save it as MSFT.csv. However, my code return error File " ", line 1, in _csv.Error: new-line character seen in unquoted fi... More on stackoverflow.com
🌐 stackoverflow.com
pandas - How to download a csv file in Python - Stack Overflow
I am trying to download a csv file from the url https://qubeshub.org/publications/1220/supportingdocs/1#supportingdocs . the file is Elephant Morphometrics and Tusk Size-originaldata-3861.csv I have More on stackoverflow.com
🌐 stackoverflow.com
How to download .csv file, produced by pandas df, on click of a simple button?
You can't set the download folder from Python code, that's a browser thing. You also can't return a string in this case you need to return a Response object: https://flask.palletsprojects.com/en/2.3.x/api/#response-objects This may also be helpful: https://flask.palletsprojects.com/en/2.3.x/api/#flask.make_response response = make_response(df.to_csv(pth)) response.headers["Content-Disposition"] = "attachment; filename=export.csv" response.headers["Content-type"] = "text/csv" response output I've never used it but this may be the most direct means: https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_file there is also https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_from_directory if the file is on disk already. You don't have to write the file to disk, you can use one of the above options with binary data, but I'm not familiar enough with pandas to say how to do that. More on reddit.com
🌐 r/flask
4
3
May 26, 2023
Fastest way to export a large dataframe to a csv file?
That's strange it shouldn't be that bad, is it only text/numbers? Have you tried using pandas More on reddit.com
🌐 r/learnpython
7
2
August 23, 2018
🌐
Streamlit
docs.streamlit.io › knowledge-base › using-streamlit › how-download-pandas-dataframe-csv
How to download a Pandas DataFrame as a CSV? - Streamlit Docs
Python · import streamlit as st import pandas as pd df = pd.read_csv("dir/file.csv") @st.cache_data def convert_df(df): return df.to_csv(index=False).encode('utf-8') csv = convert_df(df) st.download_button( "Press to Download", csv, "file.csv", ...
🌐
W3Schools
w3schools.com › python › pandas › pandas_csv.asp
Pandas Read CSV
CSV files contains plain text and is a well know format that can be read by everyone including Pandas. In our examples we will be using a CSV file called 'data.csv'. Download data.csv.
🌐
GeeksforGeeks
geeksforgeeks.org › export-pandas-dataframe-to-a-csv-file
Export Pandas dataframe to a CSV file - GeeksforGeeks
March 12, 2025 - Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. Python3 # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' #
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › saving-a-pandas-dataframe-as-a-csv
Saving a Pandas Dataframe as a CSV - GeeksforGeeks
import pandas as pd nme = ["Aparna", ... df = pd.DataFrame(data) df ... Here, we simply export a Dataframe to a CSV file using df.to_csv()....
Published   January 13, 2026
Find elsewhere
🌐
Csvgetter
csvgetter.com › blog › read-a-csv-file-in-python-pandas
Read a CSV File in Python Pandas
June 24, 2024 - This guide will show you how to use pandas to read a CSV file from both your local directory, and from an online source. We will also include some extra information on how to make your CSV files available for download with CSV Getter. If you have installed python or python3, then this can be ...
🌐
Quora
quora.com › How-do-I-write-a-code-in-Python-that-downloads-a-csv-file-from-the-web
How to write a code in Python that downloads a .csv file from the web - Quora
If content is gzipped/compressed, requests/pandas handle Content-Encoding automatically; for other compression (zip), download and then extract. These patterns cover most use cases for downloading CSV files from the web in Python.
Top answer
1 of 4
28

If you're trying to write this data to a CSV file, you can first download it using requests.get, then save each line to a CSV file.

import csv
import requests

url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'
response = requests.get(url)        

with open('out.csv', 'w') as f:
    writer = csv.writer(f)
    for line in response.iter_lines():
        writer.writerow(line.decode('utf-8').split(','))

Alternatively, if you have pandas installed (pip install --user pandas), you can load data by passing a URL directly.

import pandas as pd

df = pd.read_csv(url)   
df.head()

    timestamp    open    high     low   close  adjusted_close    volume  dividend_amount  split_coefficient
0  2019-06-19  135.00  135.93  133.81  135.69          135.69  17946556              0.0                1.0
1  2019-06-18  134.19  135.24  133.57  135.16          135.16  25908534              0.0                1.0
2  2019-06-17  132.63  133.73  132.53  132.85          132.85  14517785              0.0                1.0
3  2019-06-14  132.26  133.79  131.64  132.45          132.45  17821703              0.0                1.0
4  2019-06-13  131.98  132.67  131.56  132.32          132.32  17200848              0.0                1.0

df.to_csv('out.csv')
2 of 4
7

You can achieve it via requests as

import os
import requests

def download_file(url, filename):
    ''' Downloads file from the url and save it as filename '''
    # check if file already exists
    if not os.path.isfile(filename):
        print('Downloading File')
        response = requests.get(url)
        # Check if the response is ok (200)
        if response.status_code == 200:
            # Open file and write the content
            with open(filename, 'wb') as file:
                # A chunk of 128 bytes
                for chunk in response:
                    file.write(chunk)
    else:
        print('File exists')

You can call the function with your url and filename that you want. In your case it would be:

url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'
filename = 'MSFT.csv'
download_file(url, filename)

Hope this helps.

🌐
Medium
medium.com › @amiri.mccain › use-python-to-read-and-download-a-large-csv-from-a-url-03a8f3062a4e
Use Python to Read and Download a Large CSV from a URL | by Amiri McCain | Medium
January 23, 2024 - Replacing NaN null fields with the string “null” fixed the issue (e.g. NULL_IF = (‘NULL', ‘null')in the FILE FORMAT object in Snowflake). Since Snowflake is outside the scope of this article, I plan on discussing this a little more in a future article. ... import pandas as pd import numpy as np import os # Download CSV with read_csv df = pd.read_csv('https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv', \ sep='\t', low_memory=False)
🌐
Reddit
reddit.com › r/flask › how to download .csv file, produced by pandas df, on click of a simple button?
r/flask on Reddit: How to download .csv file, produced by pandas df, on click of a simple button?
May 26, 2023 -

I am learning web dev with flask. So far I have loved flask with its simplistic framework, Django was taking too much of my time especially since I don't main web development.

Please help me understand why I can't download my dataframe to csv using the view function in flask.

My flask app for creating an output.csv from a simple dataframe - df = pd.DataFrame({"id":[1,2,3],"name":['x','y','z']}).

Issues:

  • Linux has / whilst windows uses . How would I account for this exactly when choosing a download folder?

  • Is there a way to dynamically set a downloads folder based on the client's computer?

  • Must the view function always return a string? I am getting the error TypeError: The view function for 'show_data' did not return a valid response. The function either returned None or ended without a return statement.

One last confusion on "downloads":

  • I have scoured through several download and upload tutorials on flask. For download, does the file actually need to exist on server, unlike producing one from pandas?

#./df_to_csv.py
from flask import *
import pandas as pd
from tkinter import filedialog as fd

app = Flask(__name__)

@app.route('/')
def open_page():
    return render_template('btn.html')

@app.route('/get_data',methods=['GET','POST'])
def show_data():
    if request. Method == 'POST':
        f = './df_output.csv'
        df = pd.DataFrame({"id":[1,2,3],"name":['x','y','z']})
        # df.to_csv(f"{f}")
        pth = fd.askdirectory() + "/test.csv"
        return df.to_csv(pth)

if __name__ == '__main__':
    app.run(debug=True)

Here is my corresponding simple html form:

<!-- ./templates/btn.html -->

<form action="http://localhost:5000/get_data"
method="post"
enctype="multipart/form-data"
>
<input type="submit" value="Download">
</form>

Many thanks for your guidance.
Top answer
1 of 2
2
You can't set the download folder from Python code, that's a browser thing. You also can't return a string in this case you need to return a Response object: https://flask.palletsprojects.com/en/2.3.x/api/#response-objects This may also be helpful: https://flask.palletsprojects.com/en/2.3.x/api/#flask.make_response response = make_response(df.to_csv(pth)) response.headers["Content-Disposition"] = "attachment; filename=export.csv" response.headers["Content-type"] = "text/csv" response output I've never used it but this may be the most direct means: https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_file there is also https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_from_directory if the file is on disk already. You don't have to write the file to disk, you can use one of the above options with binary data, but I'm not familiar enough with pandas to say how to do that.
2 of 2
1
Hi, in my current website I convert data from db to json and create option to download it. You can try to change it to csv format. I have in flask api endpoint which returns return jsonify(results_data), 200 where result_data is dict. in js I have this: async function loadResults(){ return await (fetch('/api/get_results/', {method: "GET"})); } get buton by id button.addEventListener('click', async () =>{ let response = []; const downloadLink = some 'a' tag try{ response = await loadResults(); } catch (e){ console.log(e) } const results = await response.json(); const blob = new Blob([JSON.stringify(results, null, 2)], { type: 'application/json' }); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = 'data.json'; downloadLink.textContent = 'Download JSON'; downloadLink.style.display = 'block'; });
🌐
Earth Data Science
earthdatascience.org › home
Import CSV Files Into Pandas Dataframes | Earth Data Science - Earth Lab
September 15, 2020 - However, when working with larger datasets, you will want to import data directly into pandas dataframes from .csv files. To import data into pandas dataframes, you will need to import the pandas package, and you will use the earthpy package to download the data files from the Earth Lab data repository on Figshare.com.
🌐
Data36
data36.com › home › pandas tutorial 1: pandas basics (reading data files, dataframes, data selection)
Pandas Tutorial 1: Pandas Basics (read_csv, DataFrame, Data Selection, etc.)
May 26, 2022 - But you don’t want to download this data file to your computer, right? You want to download it to your server and then load it to your Jupyter Notebook. It only takes two more steps. Go back to your Jupyter Notebook and type this command: !wget 46.101.230.157/dilan/pandas_tutorial_read.csv
🌐
Plus2Net
plus2net.com › python › pandas-student.php
Creating sample Pandas DataFrame student from Excel, CSV or MySQL or to copy the code
February 5, 2019 - ⇓ Download sample ( Excel file ) student.xlsx ⇓ csv file: student.csv ⇓ Download sample ( JASON file ) student.json ⇓ .html file: student.html ⇓Download sample XML file: student.xml Copy to clipboard ( DataFrame ) import pandas as pd dt={'id': {0: 1,1: 2,2: 3,3: 4,4: 5,5: 6,6: 7,7: 8,8: 9,9: 10,10: 11,11: 12, 12: 13,13: 14,14: 15,15: 16,16: 17,17: 18,18: 19,19: 20,20: 21,21: 22, 22: 23,23: 24,24: 25,25: 26,26: 27,27: 28,28: 29,29: 30,30: 31,31: 32,32: 33, 33: 34,34: 35}, 'name': {0: 'John Deo',1: 'Max Ruin',2: 'Arnold',3: 'Krish Star',4: 'John Mike', 5: 'Alex John',6: 'My John Rob',7
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.5 documentation - PyData |
A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any os.PathLike. By file-like object, we refer to objects with a read() method, such as a file handle (e.g. via builtin open function) or StringIO. ... Character or regex pattern to treat as the delimiter. If sep=None, the C engine cannot automatically detect the separator, but the Python ...
🌐
datagy
datagy.io › home › pandas tutorials › pandas reading & writing data › pandas dataframe to csv file – export using .to_csv()
Pandas Dataframe to CSV File - Export Using .to_csv() • datagy
December 15, 2022 - Use Python and Pandas to export a dataframe to a CSV file, using .to_csv, including changing separators, encoding, and missing values.
🌐
Kaggle
kaggle.com › code › arkaung › download-csv-file
Download csv file | Kaggle
March 17, 2019 - Explore and run AI code with Kaggle Notebooks | Using data from No attached data sources