首先,您要编写与模式是否匹配的行。否则,您只写出匹配的行。
其次,在阅读各行并编写结果之间,您需要截断文件(
f.seek(0)然后单击
f.truncate()),或关闭原始文件并重新打开。选择前者,我将得到类似以下内容:
fpath = os.path.join(thisdir, filename)with open(fpath, 'r+') as f: lines = f.readlines() f.seek(0) f.truncate() for line in lines: if '<a href="' in line: for test in filelist: pathmatch = file_match(line, test) if pathmatch is not None: repstring = filelist[test] + pathmatch line = line.replace(test, repstring) f.write(line)



