file 'with ... as'
This commit is contained in:
parent
e539d2a428
commit
5dec1eb382
55
links.py
55
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")
|
||||
|
|
Loading…
Reference in New Issue