'Create relative hyperlinks in Excel for a specified path using Python
I have a pandas DataFrame, with one column FullPath containing the directory tree listing of a specified path. I am saving this to an Excel spreadsheet:
FullPath
C:\Users\aaron\folder1
C:\Users\aaron\folder1\191090-MS-0001_1.pdf
C:\Users\aaron\folder1\folder3
C:\Users\aaron\folder1\folder3\191090-MS-0001_1.pdf
C:\Users\aaron\folder2
C:\Users\aaron\folder2\191090-MS-0005_1.pdf
I would like to change the values under FullPath so that (A) they appear as hyperlinks within the spreadsheet and (B) they are relative links.
Is this possible?
The Python code to generate this is:
import os
import pandas as pd
def dir_tree(root):
"""Create list of all file/folder paths"""
dir_list = []
for root, dirs, files in os.walk(root):
for d in dirs:
dir_list.append(os.path.join(root, d))
for f in files:
dir_list.append(os.path.join(root, f))
return dir_list
# Target directory
PATH = r'C:\Users\aaron'
# Dataframe of directory tree
dir_tree_df = pd.DataFrame({"FullPath" : dir_tree(PATH)})
# Output to Excel
dir_tree_df.to_excel('output.xlsx')
EDIT:
Some context on what I'm trying to do - basically the Python script to generate this will be run on SSDs containing files/folders (I'll just update the PATH variable in the script above before running), and the resulting Excel will be stored within that SSD.
The idea is that someone plugs the SSD into their machine, opens up the Excel file within it, and then can click on any of the paths under FullPath and it'll open that folder, or attempt to open the file within the SSD.
Also - I've discovered that the below will actually convert the links to hyperlink when outputted to Excel. However my concern is that the full path of SSDs will change depending on the machine, if I'm not mistaken (the drive letters)? Is there a way for me to accommodate this?
dir_tree_df['FullPath'] = '=HYPERLINK("' + dir_tree_df['FullPath'] + '")'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
