如何只替换文档行中字符串的第一次或第二次出现?

时间:2017-08-09 17:50:11

标签: python

我有一个文件,其中列出了两次特定的字符串。 我只想改变第一行或只改变第二行。我该如何指定?

我看了一些例子,我看到有人这样做:

line.replace('8055', '8006')

更改为:

line.replace('8055', '8006', 1) # 1 means only change the first occurence of this string 8005 in a line

这是我的代码:

    try:
        source = '//' + servername + r'/c$/my dir/mydocument.config'
        with open(source,'r') as f: # you must first read file and save lines
            newlines = []
            for line in f.readlines():
                newlines.append(line.replace('8055', '8006', 1))  # 1 means only change the first occurence of this string 8005 in a line
        with open(source, 'w') as f: # then you can open and write
            for line in newlines:
                f.seek(
                f.write(line)
        f.close()
    except:
        pass

为什么这不起作用? 这会改变两行,而不只是1。

更新

    try:
        line_changed = False
        source = '//' + servername + r'/c$/my dir/myfile.config'
        with open(source,'r') as f: # you must first read file and save lines
            newlines = []
            for line in f.readlines():
                if not line_changed:
                    old_line = line
                    line = line.replace('8055', '8006', 1)  # 1 means only change the first occurence of this string 8005 in a line
                    if not old_line == line:
                        line_changed = True
                newlines.append(line)
        with open(source, 'w') as f: # then you can open and write
            for line in newlines:
                f.write(line)
        f.close()
    except:
        pass

2 个答案:

答案 0 :(得分:1)

line_changed = False
with open(source,'r') as f: # you must first read file and save lines
    newlines = []
    for line in f.readlines():
        if not line_changed:
            old_line = line
            line = line.replace('8055', '8006', 1)
            if not old_line == line:
                line_changed = True
        newlines.append(line)

这将使程序在第一次出现更改后停止寻找要更改的其他行。

答案 1 :(得分:0)

此代码正常工作:)

让我们说你有这个档案:

myfile.txt的

8055 hello 8055 8055
8055
hello 8055 world 8055
hi there

运行程序后,它具有以下内容:

8006 hello 8055 8055
8006
hello 8006 world 8055
hi there

也就是说,您的代码只替换每行中的一个。这就是line.replace(...)中发生的事情。

如果您只想在整个文档中替换它,那么您可能希望针对包含整个文件内容的字符串调用replace()方法!

还有其他方法可以做到这一点 - 例如,您可以为每一行调用replace(),一旦一行有替换,然后在迭代文件的其余部分时停止调用该方法。由你决定什么是有道理的。