Python and Jupyter save and download CSV file

Jupyter is perfect for interactive coding, visualization development, automation tests and semi-technical users. Most of the users like to have a way to save and download part of the results from the Jupyter execution. There is a simple and efficient way to save and download CSV, JSON, XML or whatever file format you need. In this article we will cover saving and downloading CSV file from Jupyter Notebook.

Note: This article assumes that users want to have downloadable link to several files. They don't have any special access to the server(SSH, SFTP) except the downloadable links from Jupyter.

Saving CSV/JSON/text file with Python

First we will see hot to create and save information to CSV file. Below you can find how to save CSV file to a current folder. This code can be in Jupyter Notobook or in python code(it can be module, file, egg):

csv = open("./my.csv", 'a')

for i in range(0, 20):
    element = str(i) + ";"
    written = csv.write(element)
csv.close()   

the result of the code will be new CSV file saved in the current folder:

0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;
0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;

Note: the above example write to file in append mode - because of the parameter - a. Truncation the file and then to write then you need to use - w:

Downloading file from Jupyter server

Next code should be placed in the Jupyter Notebook cell and to be executed like this:

from IPython.display import FileLink, FileLinks
FileLinks('.') #lists all downloadable files on server

The result will create links to all files in current folder. The files can be downloaded by right click and save link:

**my.csv**

Related Article