如何逐行替换(更新)文件中的文本 [英] how to replace (update) text in a file line by line

查看:46
本文介绍了如何逐行替换(更新)文件中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过读取每一行,测试它,然后写入是否需要更新来替换文本文件中的文本.我不想另存为新文件,因为我的脚本已经先备份了文件并对备份进行了操作.

I am trying to replace text in a text file by reading each line, testing it, then writing if it needs to be updated. I DO NOT want to save as a new file, as my script already backs up the files first and operates on the backups.

这是我到目前为止所拥有的......我从 os.walk() 得到 fpath 并且我保证路径匹配 var 正确返回:

Here is what I have so far... I get fpath from os.walk() and I guarantee that the pathmatch var returns correctly:

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)

但最终发生的是我只得到了几行(正确更新,请注意,但从文件的前面重复)更正.我认为这是一个范围界定问题,事实上.

But what ends up happening is that I only get a few lines (updated correctly, mind you, but repeated from earlier in the file) corrected. I think this is a scoping issue, afaict.

*另外:我想知道如何只在匹配的第一个实例中替换文本,例如,我不想匹配显示文本,只匹配底层 href.

*Also: I would like to know how to only replace the text upon the first instance of the match, for ex., I don't want to match the display text, only the underlying href.

推荐答案

首先,你想写一行,不管它是否匹配模式.否则,您只会写出匹配的行.

First, you want to write the line whether it matches the pattern or not. Otherwise, you're writing out only the matched lines.

其次,在读取行和写入结果之间,您需要截断文件(可以 f.seek(0) 然后 f.truncate()),或关闭原件并重新打开.选择前者,我最终会得到类似的结果:

Second, between reading the lines and writing the results, you'll need to either truncate the file (can f.seek(0) then f.truncate()), or close the original and reopen. Picking the former, I'd end up with something like:

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)

这篇关于如何逐行替换(更新)文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆