I'm trying to make a program which would replace tags in a markdown file (.md) as follow :
If it's an opening $
tag, replace it by \(
, if it's a closing $
tag, replace it by \)
, copy every other characters.
不幸的是,当我尝试时,写入的文件确实很奇怪。有些行被复制,而其他行则没有。首先,我的每个测试文件的第一行和最后一行都没有被复制。中间的其他行也不太好。不同行上的相同文本不会同时复制。
这是我的程序:
import os
def conv1(path):
"""convert $$ tags to \( \)"""
file = open(path, mode ='r') # open lesson with $ (.md)
new = open(path + '.tmp', mode = 'w') # open blank file
test = 0
for lines in file:
line = file.readline()
i = 0
length = len(line)
while i < length:
if line[i] == '$':
if test % 2 == 0: # replace opening tag
line = line[:i] + '\(' + line [i + 1:]
elif test % 2 == 1: # replace closing tag
line = line[:i] + '\)' + line [i + 1:]
test +=1
i += 2
length += 1
else :
i += 1
new.write(line + '\n')
file.close()
new.close()
os.rename(str(path) + '.tmp', str(path))
print('Done!')
您知道如何解决我的问题吗?
提前致谢
EloiLmr