5

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

dshefman
  • 937
  • 9
  • 19

1 Answers1

5

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})
PythonSherpa
  • 2,560
  • 3
  • 19
  • 40
  • Thank you. I tested out your code and it fixes the first part of the problem. However, now I get an error message from Jupyter Notebook saying "Jupyter Notebook is unable to open this file type." Is there a simple way to open the file using the default application (in this case Word)? Or, am I limited to filetypes compatible with Jupyter Notebook? – dshefman Aug 15 '18 at 17:09
  • Weird, I cannot replicate your error message. The code works fine on my computers (Mac & Windows) for both .docx as jpg/png – PythonSherpa Aug 15 '18 at 18:12
  • Thanks for the helpful answer. I have a bit of a strange issue - when I click the links in the dataframe (leading to local html files), they are not displayed. However if I copy-paste the URL - it works. I am using firefox. Any idea why this is happening? – soungalo Jul 07 '20 at 08:41