我有一個在其中列出了一定字符串的文檔兩次。 我只想更改第一行或僅更改第二行。我如何指定?如何僅替換文檔行中第一次或第二次出現的字符串?
我已經看過例子,我看到人們做這樣的事情:
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()'時,它都會執行一次替換。 –