Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a table with clickable hyperlink to a local file in pandas & Jupyter Notebook

I learned from this post that I can link to a website in a Jupyter Notebook: How to create a table with clickable hyperlink in pandas & Jupyter Notebook

So, I tried to adapt the code to create a dataframe with links to local files. However, when I click on the hyperlinks from the code below, nothing happens.

How do I fix the code below for the hyperlinks to work?

import os
import pandas as pd

data = [dict(name='file1', 
        filepath='C:/Users/username/Documents/file1.docx'),
        dict(name='file2', 
        filepath='C:/Users/username/Documents/file2.docx')]

df = pd.DataFrame(data)

def make_clickable(url):
    name= os.path.basename(url)
    return '<a href="file:///{}">{}</a>'.format(url,name)

df.style.format({'filepath': make_clickable})

enter image description here

like image 262
dshefman Avatar asked Aug 15 '18 00:08

dshefman


People also ask

How do you make a link clickable in Python?

link() method in Python is used to create a hard link. This method creates a hard link pointing to the source named destination.

How do I add a element to a DataFrame pandas?

You can add rows to the pandas dataframe using df. iLOC[i] = ['col-1-value', 'col-2-value', ' col-3-value '] statement.


1 Answers

Your browser is actually blocking this. You probably see an error message like "Not allowed to load local resource" in your browser's developer tools (Chrome, Firefox, Safari). Changing this would expose you to serious security risks.

An alternative could be to put the files you want to access in the same working directory as your Jupyter Notebook. For instance, if you add a folder named "Documents" in your working directory, you can then link to the files like this:

http://localhost:8888/notebooks/Documents/file1.docx

Your code would be:

import os
import pandas as pd

data = [dict(name='file1', 
    filepath='Documents/file1.docx'),
    dict(name='file2', 
    filepath='Documents/file2.docx')]

df = pd.DataFrame(data)

def make_clickable(url):
    name= os.path.basename(url)
    return '<a href="{}">{}</a>'.format(url,name)

df.style.format({'filepath': make_clickable})
like image 178
PythonSherpa Avatar answered Oct 20 '22 09:10

PythonSherpa