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')
Answer from coldspeed95 on Stack Overflow
🌐
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 - The solution provided uses Python to download a large CSV into a Pandas dataframe and then saves that large dataframe into “n” number of smaller CSV files and then finally the smaller CSV files are copied and converted to Parquet files. ... Accessing and downloading a CSV from a URL using Python is typically pretty straightforward.
Discussions

How to read a CSV file from a URL with Python? - Stack Overflow
Supports Claude Code, Cursor, Codex, Windsurf and more. Explore Stack Overflow for Agents ... The future of development is... ... 43 Read .csv file from URL into Python 3.x - _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) 3 Python twill: download file ... More on stackoverflow.com
🌐 stackoverflow.com
urllib - Download csv file through python (url) - Stack Overflow
I work on a project and I want to download a csv file from a url. I did some research on the site but none of the solutions presented worked for me. The url offers you directly to download or open the file of the blow I do not know how to say a python to save the file (it would be nice if I ... More on stackoverflow.com
🌐 stackoverflow.com
Automatically download CSV from website (Python)
It seems they've changed the way the download button works. There is some complicated obfuscated javascript that fires off the download. The data seems to come from a different endpoint which you can see loaded in the network tab of your browser's developer tools when you reload the page. This script dumps all that data into a csv, not sure it helps you or not. import requests import pandas as pd data_url = 'https://fundcentres.lgim.com/srp/api/fund-centre/1/?audience=79&language=1' data = requests.get(data_url).json() clean = [] for fund in data['funds']: for share_class in fund['share_classes']: fixed = fund['data']+share_class['data'] clean.append(fixed) fund_detail_columns = [x['label'] for x in data['metadata']['fund_fields']] share_class_columns = [x['label'] for x in data['metadata']['share_class_fields']] columns = fund_detail_columns + share_class_columns df = pd.DataFrame(clean,columns=columns) df.to_csv('fund_data.csv',index=False) More on reddit.com
🌐 r/webscraping
6
4
January 20, 2022
Use python requests to download CSV - Stack Overflow
Save this answer. ... Show activity on this post. To simplify these answers, and increase performance when downloading a large file, the below may work a bit more efficiently. Copyimport requests from contextlib import closing import csv from codecs import iterdecode url = "http://download-and-process-csv-efficiently/python... More on stackoverflow.com
🌐 stackoverflow.com
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.

🌐
Delft Stack
delftstack.com › home › howto › python › python download csv from url
How to Download CSV From URL in Python | Delft Stack
February 12, 2024 - CSV file successfully downloaded and saved as 'data.csv'. One effective method involves using the requests library for handling HTTP requests and the native csv module for CSV file processing. This combination offers simplicity and versatility, making it a preferred choice for Python developers seeking an efficient way to download CSV files from URLs.
🌐
Codingdeeply
codingdeeply.com › home › easy python tutorial: download csv from url in a few simple steps
Easy Python Tutorial: Download CSV from URL in a Few Simple Steps
February 23, 2024 - Download the File: Now that you have specified the URL and file path, you can use the ‘urllib.request.urlretrieve’ function to download the CSV file from the URL and save it to your local machine.
🌐
Medium
medium.com › @mudassar_lhr › how-to-download-the-csv-file-from-url-using-python-650eae6d3478
How to download the CSV file from URL using Python | by Mudassar | Medium
May 27, 2022 - PIP is a package manager for python. You can use PIP to install a module on your computer. So, we are going to write the first line of downloading code which is: “import request “ After wrote this command, you will notice that there is an error on this line of code. This is because, we have to install this module. As I mentioned above some modules are built-in and some are need to install. For download the csv file we have to install the package “requests” For this you have to go to the Terminal: write the command:
Find elsewhere
🌐
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
Answer (1 of 3): The easiest and fastest option is as follows. This will download the file, parse it and return a tabular object, so-called DataFrame. With that you can directly work with the data and apply statistics to it etc. [code]# install pandas: run pip install pandas before you run this ...
🌐
Real Python
realpython.com › python-download-file-from-url
How to Download Files From URLs With Python – Real Python
January 25, 2025 - You can download a file using a URL in Python by using the urlretrieve() function from the urllib library or the requests.get() method from the requests library to fetch the file and save it locally.
🌐
GitHub
gist.github.com › krisrak › 2cd4230682997d399c33a1b24c266521
Python script to download urls in a csv file · GitHub
The urls can be images or video files, and the script will create a folder in the same location and download the files to it. Usage: /usr/bin/python picodash_export_url_download.py <csv_filename> <column_header_name>
🌐
Reddit
reddit.com › r/webscraping › automatically download csv from website (python)
r/webscraping on Reddit: Automatically download CSV from website (Python)
January 20, 2022 -

I need to be able to download a file each day from the following site:
https://fundcentres.lgim.com/uk/en/fund-centre/PMC/

There is a link that says 'Download Data' which then presents a pop-up with 'All Fund Data'.

Normally I use Python requests but this is more complicated than I've dealt with. I've searched different way to try to replicated the POST request but can't quite understand what I'm missing.

Any help would be appreciated!

Top answer
1 of 14
128

This should help:

import csv
import requests

CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'


with requests.Session() as s:
    download = s.get(CSV_URL)

    decoded_content = download.content.decode('utf-8')

    cr = csv.reader(decoded_content.splitlines(), delimiter=',')
    my_list = list(cr)
    for row in my_list:
        print(row)

Ouput sample:

['street', 'city', 'zip', 'state', 'beds', 'baths', 'sq__ft', 'type', 'sale_date', 'price', 'latitude', 'longitude']
['3526 HIGH ST', 'SACRAMENTO', '95838', 'CA', '2', '1', '836', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '59222', '38.631913', '-121.434879']
['51 OMAHA CT', 'SACRAMENTO', '95823', 'CA', '3', '1', '1167', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68212', '38.478902', '-121.431028']
['2796 BRANCH ST', 'SACRAMENTO', '95815', 'CA', '2', '1', '796', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68880', '38.618305', '-121.443839']
['2805 JANETTE WAY', 'SACRAMENTO', '95815', 'CA', '2', '1', '852', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '69307', '38.616835', '-121.439146']
[...]

Related question with answer: https://stackoverflow.com/a/33079644/295246


Edit: Other answers are useful if you need to download large files (i.e. stream=True).

2 of 14
40

To simplify these answers, and increase performance when downloading a large file, the below may work a bit more efficiently.

import requests
from contextlib import closing
import csv
from codecs import iterdecode

url = "http://download-and-process-csv-efficiently/python.csv"

with closing(requests.get(url, stream=True)) as r:
    reader = iterdecode(csv.reader(r.iter_lines(), 'utf-8'), 
                        delimiter=',', 
                        quotechar='"')
    for row in reader:
        print(row)

By setting stream=True in the GET request, when we pass r.iter_lines() to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader.

This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.

🌐
Educative
educative.io › home › courses › data wrangling with python › loading a csv dataset from a url
Loading CSV Datasets from URLs with pandas in Python
Learn how to load CSV data from a URL using pandas in Python, including techniques to select columns, limit rows, and skip unwanted rows for effective data analysis.
🌐
Stack Overflow
stackoverflow.com › questions › 63925247 › python-pandas-how-to-save-csv-file-from-url
Python - Pandas : how to save csv file from url - Stack Overflow
September 16, 2020 - so I'm trying to get a csv file with requests and save it to my project: import requests import pandas as pd import csv def get_and_save_countries(): url = 'https://www.trackcorona.live/api/
🌐
Reddit
reddit.com › r/learnpython › how to download a csv file from an https website
r/learnpython on Reddit: How to download a CSV file from an HTTPS website
June 17, 2020 -

So I am working on a pretty large project at work where I want to automate the entire process of checking through thousands of lines of transactions every month. I'd like to also download and save the files that we need for it within the program.

The website is a secure financial reporting site that requires a username and password to enter. I'm currently using the requests library. When I do a simple get request on the URL i get back a lot of what I believe are javascript objects. Perhaps I am mistaken, but I believe i need the specific web address of the csv download file.

I watched and read a number of tutorials and most started by "copy link address" . However, this only gives me the address of the image of the CSV icon.

Basically, Im pretty lost here. The website is dynamic, you can add or subtract columns, filter, add excel type formulas and then export whatever your results are.

So I have 3 questions, how do I get the appropriate link to download the file? am I just completely out of my depth here on how this whole thing works? And if so are there any good tutorials to start learning enough to get this to work.

🌐
Epidemiology
epidemiology.tech › home › downloading a csv from rest api using python requests
Downloading a CSV from REST API using Python Requests » Epidemiology and Technology
January 12, 2024 - r = requests.get(fullurl, auth=HTTPBasicAuth(username, password) , timeout=(20, 300)) r.raise_for_status() if (r.status_code == 200): responseContentType = r.headers.get('content-type') print(responseContentType) if (responseContentType =='text/csv') : r.encoding = 'utf-8' try: csvfile = open(localfilename, 'wt', encoding='utf-8') # wt = write as text csvfile.write(r.text) print(localfilename + " SAVED") logger.info("File Saved : %s", str(localfilename)) except: print("Something went wrong when writing to the file") logger.error("Something went wrong when writing to the file :", exc_info=True)