Skip to main content

text/fix_whitespace

1#!/usr/bin/env python3
2"""
3Remove extra whitespace from a text file.
5When I copy/paste text from the web into Obsidian, it's often inserted
6with a lot of additional whitespace, e.g. text like
8 hello\n\nworld
10becomes
12 hello\n\n \n\nworld
14This script cleans up some of this extraneous whitespace for me.
15"""
17import re
18import sys
21if __name__ == '__main__':
22 try:
23 path = sys.argv[1]
24 except IndexError:
25 sys.exit(f"Usage: {__file__} <path>")
27 with open(path, "r") as infile:
28 text = infile.read()
30 text = re.sub(r"\n\n\s*\n\n", "\n\n", text)
32 with open(path, "w") as outfile:
33 outfile.write(text)