From b224665c24c0079dad9d76bfa66a7adf02a71c83 Mon Sep 17 00:00:00 2001 From: geritol Date: Sat, 30 Sep 2017 14:59:20 +0200 Subject: [PATCH] now possible to update the same file --- utils/housekeep.py | 2 -- utils/write_file.py | 36 +++++++++++++++++++++++++----------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/utils/housekeep.py b/utils/housekeep.py index b21b21e..c0fa1ab 100644 --- a/utils/housekeep.py +++ b/utils/housekeep.py @@ -21,8 +21,6 @@ try: choices = ['rating', 'title', 'author', 'year'], help='defaults to rating') flags = parser.parse_args() - #argparse.ArgumentParser(parents=[tools.argparser]).parse_args() - print(flags) except ImportError: flags = None diff --git a/utils/write_file.py b/utils/write_file.py index 86c17fb..af19e58 100644 --- a/utils/write_file.py +++ b/utils/write_file.py @@ -1,3 +1,7 @@ +from shutil import copyfile +import os + + def render_book_line(book_object): book = book_object book['rating'] = '?' if not 'rating' in book else book['rating'] @@ -12,27 +16,37 @@ def render_book_line(book_object): # TODO: refine this logic def render(in_file, out_file, library): + """ + This renders the file to the out_file location + savig the new file to tmp_file location, the copying it to out-file and deleting tmp_file + this is done to prevent issues if the in and the out file are the same + """ + tmp_file = './.tmp-file.md' + open(tmp_file, 'a').close() books_not_reached = True - with open(out_file, 'w') as out_file: + with open(tmp_file, 'w') as out_file_tmp: with open(in_file) as original_file: for line in original_file: if line.strip() in library: - if not books_not_reached: out_file.write('\n') + if not books_not_reached: out_file_tmp.write('\n') books_not_reached = False # render chapter and start of the table - out_file.write(line) + out_file_tmp.write(line) if len(library[line.strip()]) > 0: - out_file.write('| Name | Author | Goodreads Rating | Year Published | \n') - out_file.write('|------|--------|------------------|----------------| \n') + out_file_tmp.write('| Name | Author | Goodreads Rating | Year Published | \n') + out_file_tmp.write('|------|--------|------------------|----------------| \n') # render books for book in library[line.strip()]: - out_file.write(render_book_line(book)) + out_file_tmp.write(render_book_line(book)) elif books_not_reached: - out_file.write(line) + out_file_tmp.write(line) elif line.startswith('## License'): - out_file.write('\n') - out_file.write('\n') - out_file.write(line) - books_not_reached = True \ No newline at end of file + out_file_tmp.write('\n') + out_file_tmp.write('\n') + out_file_tmp.write(line) + books_not_reached = True + + copyfile(tmp_file, out_file) + os.remove(tmp_file) \ No newline at end of file