2017-08-09 120 views
-2

我有一個在其中列出了一定字符串的文檔兩次。 我只想更改第一行或僅更改第二行。我如何指定?如何僅替換文檔行中第一次或第二次出現的字符串?

我已經看過例子,我看到人們做這樣的事情:

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 
+1

你會得到什麼錯誤?它以什麼方式不起作用? – thaavik

+0

它使每行更換1個。所以每次在新行上調用'line.replace()'時,它都會執行一次替換。 –

回答

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) 

這將使程序在第一次發生更改後不再查找要更改的行。

+0

這是刪除我改變第一行後的所有行。 – Prox

+0

@Prox我更新了代碼,現在它將在更改一行後繼續讀取。 –

+0

我在頂部添加了我正在嘗試的內容。 UPDATE部分下的代碼是否正確?這不會改變我的任何事情。 – Prox

0

此代碼工作:)

比方說,你有這樣的文件:

myfile.txt的

8055 hello 8055 8055 
8055 
hello 8055 world 8055 
hi there 

A壓腳提升運行程序,它具有以下內容:

8006 hello 8055 8055 
8006 
hello 8006 world 8055 
hi there 

也就是說,你的代碼只在每行更換項目1。這就是line.replace(...)中發生的情況。

如果您只希望它替換整個文檔中的一個,那麼您應該針對整個文件內容的字符串調用replace()方法!

還有其他方法可以做到這一點 - 例如,您可以爲每一行調用replace(),並且一旦有一行有替換,當迭代文件的其餘部分時停止調用該方法。由你決定什麼是有道理的。

相關問題