我试图通过读取每一行,测试它,然后写,如果它需要更新,替换文本文件中的文本.我不想保存为新文件,因为我的脚本已经先备份文件并对备份进行操作.
这是我到目前为止...我从os.walk()得到fpath,我保证pathmatch var正确返回:
fpath = os.path.join(thisdir, filename)
with open(fpath, 'r+') as f:
for line in f.readlines():
if '<a href="' in line:
for test in filelist:
pathmatch = file_match(line, test)
if pathmatch is not None:
repstring = filelist[test] + pathmatch
print 'old line:', line
line = line.replace(test, repstring)
print 'new line:', line
f.write(line)
Run Code Online (Sandbox Code Playgroud)
但最终发生的事情是,我只得到了几行(正确更新,请注意,但在文件的前面重复)已更正.我认为这是一个范围界定的问题.
*另外:我想知道如何仅在匹配的第一个实例上替换文本,例如,我不想匹配显示文本,只有底层href.
hug*_*own 10
with open(filename, "r") as f:
lines = (line.rstrip() for line in f)
altered_lines = [some_func(line) if regex.match(line) else line for line in lines]
with open(filename, "w") as f:
f.write('\n'.join(altered_lines) + '\n')
Run Code Online (Sandbox Code Playgroud)
首先,您想要写一行是否与模式匹配.否则,您只会写出匹配的行.
其次,在读取行和写入结果之间,您需要截断文件(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)
Run Code Online (Sandbox Code Playgroud)