2014-11-06 34 views
0

我知道這裏存在很多關於使用python 2查找和替換文件中的文本的問題。然而,作爲python的一個非常新的東西,我不理解語法並可能是目的也會有所不同。Python 2.x查找並替換多行文本

我在尋找的東西非常簡單的代碼行作爲在Linux shell腳本

sed -i 's/find/replace/' *.txt 
sed -i 's/find2/replace2/' *.txt 

可以此代碼的工作,以取代多行文本

with open('file.txt', 'w') as out_file: 
    out_file.write(replace_all('old text 1', 'new text 1')) 
    out_file.write(replace_all('old text 2', 'new text 2')) 

而且,似乎有越來越另一換行符問題,我不想要。任何想法或幫助?

+0

@ inspectorG4dget我想使用同一個文件。沒有不同的讀寫文件 – gyeox29ns 2014-11-06 02:37:33

+0

這就是你需要的:http://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place – user3885927 2014-11-06 04:59:51

回答

2

因此,使用Python,最簡單的方法是將文件中的所有文本讀取到字符串中。然後使用該字符串執行任何必要的替換。然後寫了整個事情回來了同一個文件:

filename = 'test.txt' 

with open(filename, 'r') as f: 
    text = f.read() 

text = text.replace('Hello', 'Goodbye') 
text = text.replace('name', 'nom') 

with open(filename, 'w') as f: 
    f.write(text) 

replace方法適用於任何字符串替換第二個是第一個參數的任何(區分大小寫)匹配。您只需通過兩個不同的步驟即可閱讀和寫入同一個文件。

2

下面是一個快速示例。如果你想更強大的查找/替換你可以使用正則表達式,而不是與string.replace

import fileinput 
for line in fileinput.input(inplace=True): 
    newline = line.replace('old text','new text').strip() 
    print newline 

把上面的代碼中所需的文件,說sample.py,並假設您的蟒蛇在您的路徑,你可以爲運行:

python sample.py inputfile 

這將在輸入文件中用'新文本'替換'舊文本'。當然你也可以傳遞多個文件作爲參數。請參閱https://docs.python.org/2/library/fileinput.html

+0

如果我想要替換2個不同的文本實例,那麼這是正確的? 'newline = line.replace('old text 1','new text 1')。strip() newline = line.replace('old text 2','new text 2')。strip寫了2行文本替換命令。 – gyeox29ns 2014-11-06 18:55:12

+0

string.replace將會替換所有的實例。如果你想限制有多少實例被替換,你可以指定另一個帶有實例數量的參數來替換。看到https://docs.python.org/2/library/string.html在最底層 – user3885927 2014-11-06 18:58:01

+0

我想我不清楚我想傳達什麼。我並不是說要替換_n_實例,而是說替換兩個或更多不同的文本行(正如我在'sed'命令中所顯示的那樣。你引用的鏈接可以限制替換文本的次數。 – gyeox29ns 2014-11-06 19:02:17