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



我有一个文档中列出了两次某个字符串。 我只想更改第一行或只更改第二行。 我该如何指定?

我看过例子,我看到人们在做这样的事情:

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
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)

这将使程序在更改第一个匹配项后停止查找要更改的其他行。

此代码正在工作:)

假设您有此文件:

我的文件.txt

8055 hello 8055 8055
8055
hello 8055 world 8055
hi there

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

8006 hello 8055 8055
8006
hello 8006 world 8055
hi there

也就是说,您的代码仅替换每行中的1 个项目。这就是line.replace(...)正在发生的事情.

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

还有其他方法可以执行此操作 - 例如,您可以为每一行调用replace(),一旦一行有替换,则在循环访问文件的其余部分时停止调用该方法。由您决定什么是有意义的。

最新更新