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()
|
incoming[wikilink] = set()
|
||||||
|
|
||||||
# open file and search for all outgoing links
|
# open file and search for all outgoing links
|
||||||
file = open(filename)
|
with open(filename) as file:
|
||||||
pre_mode = False
|
pre_mode = False
|
||||||
for line in file:
|
for line in file:
|
||||||
if re.match("```",line) != None: # toggle preformatted mode
|
if re.match("```",line) != None: # toggle preformatted mode
|
||||||
pre_mode = not pre_mode
|
pre_mode = not pre_mode
|
||||||
if pre_mode: # skip preformatted mode
|
if pre_mode: # skip preformatted mode
|
||||||
continue
|
continue
|
||||||
while re.search("\{[^{}]+\}",line):
|
while re.search("\{[^{}]+\}",line):
|
||||||
m = re.search("\{[^{}]+\}",line)
|
m = re.search("\{[^{}]+\}",line)
|
||||||
match = m.group() # matched string
|
match = m.group() # matched string
|
||||||
if match not in incoming: # create a new set for that page
|
if match not in incoming: # create a new set for that page
|
||||||
incoming[match] = set()
|
incoming[match] = set()
|
||||||
# add this file
|
# add this file
|
||||||
incoming[match].add(wikilink)
|
incoming[match].add(wikilink)
|
||||||
line = line[m.end()+1:]
|
line = line[m.end()+1:]
|
||||||
file.close()
|
|
||||||
|
|
||||||
os.chdir('../tmp/')
|
os.chdir('../tmp/')
|
||||||
# remove incoming links for:
|
# remove incoming links for:
|
||||||
|
@ -54,17 +53,15 @@ for key,links in incoming.items():
|
||||||
# print(key)
|
# print(key)
|
||||||
|
|
||||||
# open file in append mode
|
# open file in append mode
|
||||||
file = open(filename, 'a')
|
with open(filename, 'a') as file:
|
||||||
|
|
||||||
if len(links):
|
if len(links):
|
||||||
# write incoming links
|
# write incoming links
|
||||||
# print( '{} incoming links\n'.format( len(links) ) )
|
# print( '{} incoming links\n'.format( len(links) ) )
|
||||||
file.write("\n\n# incoming links\n")
|
file.write("\n\n# incoming links\n")
|
||||||
for link in links:
|
for link in links:
|
||||||
gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link)
|
gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link)
|
||||||
# print(gemlink)
|
file.write(gemlink+"\n")
|
||||||
file.write(gemlink+"\n")
|
else:
|
||||||
else:
|
print( '{}: orphan\n'.format(key) )
|
||||||
print( '{}: orphan\n'.format(key) )
|
file.write("\n\nno incoming links\n")
|
||||||
file.write("\n\nno incoming links\n")
|
|
||||||
file.close()
|
|
||||||
|
|
Loading…
Reference in New Issue