我有一个在其中列出了一定字符串的文档两次。 我只想更改第一行或仅更改第二行。我如何指定?如何仅替换文档行中第一次或第二次出现的字符串?
我已经看过例子,我看到人们做这样的事情:
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
UPDATE
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
你会得到什么错误?它以什么方式不起作用? – thaavik
它使每行更换1个。所以每次在新行上调用'line.replace()'时,它都会执行一次替换。 –