Skip to content

Instantly share code, notes, and snippets.

@ScribbleGhost
Last active January 30, 2024 14:18
Show Gist options
  • Save ScribbleGhost/d81bcaee96613434ea7f98000730637f to your computer and use it in GitHub Desktop.
Save ScribbleGhost/d81bcaee96613434ea7f98000730637f to your computer and use it in GitHub Desktop.
Got a long list of links you want to add as favorites in your web browser? Use this Python script to convert a CSV file with links to a favorite HTML file that can be imported to any Chromium browsers.
import csv
import html
def csv_to_html_bookmarks(csv_file_path, html_file_path):
header = '''<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
It will be read and overwritten.
DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
'''
footer = '</DL><p>'
def create_folder_hierarchy(folder):
return [f' <DT><H3>{html.escape(folder)}</H3>', ' <DL><p>']
def close_folders(level):
return [' </DL><p>' for _ in range(level)]
with open(csv_file_path, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
next(reader) # Skip header row
bookmarks = []
current_folder_path = []
for row in reader:
folder_path, title, url = row
folder_levels = folder_path.split('>') if folder_path else []
# Close any open folders that are not part of the current path
while current_folder_path and current_folder_path != folder_levels[:len(current_folder_path)]:
bookmarks.extend(close_folders(1))
current_folder_path.pop()
# Open new folders
for folder in folder_levels[len(current_folder_path):]:
bookmarks.extend(create_folder_hierarchy(folder))
current_folder_path.append(folder)
if title and url: # Ensuring that the row has title and URL
bookmarks.append(f' <DT><A HREF="{html.escape(url)}" ADD_DATE="0">{html.escape(title)}</A>')
# Close all remaining open folders
bookmarks.extend(close_folders(len(current_folder_path)))
with open(html_file_path, 'w', encoding='utf-8') as htmlfile:
htmlfile.write(header + '\n'.join(bookmarks) + footer)
# Example usage
csv_to_html_bookmarks('path_to_your_csv_file.csv', 'output_bookmarks.html')
Folder Path Title URL
Tech News Homepage https://www.example.com
Tech News>Gadgets Gizmodo https://www.gizmodo.com
Tech News>Science Science Daily https://www.sciencedaily.com
Learning Python Official Site https://www.python.org
Learning>Programming Stack Overflow https://stackoverflow.com
Learning>Programming>Coding Challenges LeetCode https://leetcode.com
News Homepage https://www.news.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment