我试图通过读取每一行来替换文本文件中的文本,对其进行测试,然后在需要更新时进行写入。我不想另存为一个新文件,因为我的脚本已经先备份文件并对备份进行操作。
这是我到目前为止所拥有的。。。我从os.walk()获取fpath,并保证pathmatch变量返回正确:
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)
但最终的结果是,我只得到了几行(更新正确,请注意,但重复从文件的前面)更正。我认为这是一个范围问题,阿法特。
*另外:我想知道如何只在匹配的第一个实例上替换文本,例如,我不想匹配显示文本,只匹配底层的href。
替换文件行的(相对)安全的方法。
(注意:这只替换整行,以及文件中匹配的所有行)
首先,你想写一行,不管它是否与模式匹配。否则,你只能写出匹配的行。
其次,在读取行和写入结果之间,您需要截断文件(可以
f.seek(0)
,然后f.truncate()
),或者关闭原始文件并重新打开。选择前者,我会得到如下结果:相关问题 更多 >
编程相关推荐