From 5dec1eb382033bc62f8a6653defcbbeee256bb6f Mon Sep 17 00:00:00 2001 From: sejo Date: Fri, 21 Jan 2022 19:51:30 -0600 Subject: [PATCH] file 'with ... as' --- links.py | 55 ++++++++++++++++++++++++++----------------------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/links.py b/links.py index fa5ef07..e93d516 100644 --- a/links.py +++ b/links.py @@ -25,22 +25,21 @@ for filename in os.listdir(): incoming[wikilink] = set() # open file and search for all outgoing links - file = open(filename) - pre_mode = False - for line in file: - if re.match("```",line) != None: # toggle preformatted mode - pre_mode = not pre_mode - if pre_mode: # skip preformatted mode - continue - while re.search("\{[^{}]+\}",line): - m = re.search("\{[^{}]+\}",line) - match = m.group() # matched string - if match not in incoming: # create a new set for that page - incoming[match] = set() - # add this file - incoming[match].add(wikilink) - line = line[m.end()+1:] - file.close() + with open(filename) as file: + pre_mode = False + for line in file: + if re.match("```",line) != None: # toggle preformatted mode + pre_mode = not pre_mode + if pre_mode: # skip preformatted mode + continue + while re.search("\{[^{}]+\}",line): + m = re.search("\{[^{}]+\}",line) + match = m.group() # matched string + if match not in incoming: # create a new set for that page + incoming[match] = set() + # add this file + incoming[match].add(wikilink) + line = line[m.end()+1:] os.chdir('../tmp/') # remove incoming links for: @@ -54,17 +53,15 @@ for key,links in incoming.items(): # print(key) # open file in append mode - file = open(filename, 'a') + with open(filename, 'a') as file: - if len(links): - # write incoming links -# print( '{} incoming links\n'.format( len(links) ) ) - file.write("\n\n# incoming links\n") - for link in links: - gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link) -# print(gemlink) - file.write(gemlink+"\n") - else: - print( '{}: orphan\n'.format(key) ) - file.write("\n\nno incoming links\n") - file.close() + if len(links): + # write incoming links + # print( '{} incoming links\n'.format( len(links) ) ) + file.write("\n\n# incoming links\n") + for link in links: + gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link) + file.write(gemlink+"\n") + else: + print( '{}: orphan\n'.format(key) ) + file.write("\n\nno incoming links\n")