Skip to content

Instantly share code, notes, and snippets.

@remotephone
Created February 22, 2022 01:15
Show Gist options
  • Save remotephone/cdccff6e0e0c83bfb0e60b9c4a9da7b4 to your computer and use it in GitHub Desktop.
Save remotephone/cdccff6e0e0c83bfb0e60b9c4a9da7b4 to your computer and use it in GitHub Desktop.
Python script to clean up some markdown files and turn a string into a list
# I had a bunch of markdown files in my blog that had a category value that was a string of words instead of a list
# I needed a way to parse and replace 40 lines that began with `categories:` at once
# This did it.
import re
import glob
# https://stackoverflow.com/questions/4568580/python-glob-multiple-filetypes
types = ('*.md')
files_grabbed = []
for files in types:
files_grabbed.extend(glob.glob(files))
for file in files_grabbed:
with open(file, 'r') as f:
content = f.readlines()
content2 = ""
for line in content:
if line.startswith('categories: '):
line = re.sub(r'\s', ', ', line)
line = re.sub(r':, ', ': [', line)
line = re.sub(', ,', ',', line)
line = re.sub(', $', ']\n', line)
content2 += line
print(content2)
with open(file, 'w') as f:
f.write(content2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment