Create reorganization script

1. Reads all quotes recursively from the `quotes` directory into an array.
2. Deletes the entire quotes directory.
3. For each quote ensure that there is a path for quotes/author_name/work_name/
4. Write the quote to quotes.csv in the correct directory.
This commit is contained in:
Jessica L. Hacker 2019-09-19 09:34:46 -07:00
parent 9441f80589
commit f7f14090ed

39
templates/reorganize.py Normal file
View file

@ -0,0 +1,39 @@
#!/usr/bin/python3
import os
import csv
import itertools
import shutil
import errno
# TODO: filter out quotes which are formatted incorrectly before reorganizing
quotes = []
for root, dirs, files in os.walk('quotes/'):
for name in files:
(base, ext) = os.path.splitext(name)
if ext == '.csv':
full_name = os.path.join(root, name)
with open(full_name) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='`', skipinitialspace=True)
quotes += list(csvreader)
# TODO: back up the quotes directory and implement recovery if the quote writing fails
shutil.rmtree('quotes')
for quote in quotes:
# path: ./quotes/author/work/
path = 'quotes/' + quote[1] + '/' + quote[3] + '/'
# https://stackoverflow.com/a/600612/11736197
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
with open(path + 'quotes.csv', 'a') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='`')
writer.writerow(quote)