2012-08-15 146 views
2

我在這裏要做的是: 1.從文本文件中讀取線條。 2.查找包含某個字符串的行。 3.刪除該行並將結果寫入新的文本文件。如何刪除包含特定字符串的行?

舉例來說,如果我有這樣的文字:

Starting text 
How are you? 
Nice to meet you 
That meat is rare 
Shake your body 

如果我的某些字符串爲「是」 我想要的輸出:

Starting text 
Nice to meet you 
Shake your body 

我不想像這樣:

Starting text 

Nice to meet you 

Shake your body 

我正在嘗試這樣的事情:

opentxt = open.('original.txt','w') 
readtxt = opentxt.read() 

result = readtxt.line.replace('are', '') 

newtxt = open.('revised.txt','w') 
newtxt.write(result) 
newtxt.close() 

,但似乎它不工作...

有什麼建議?任何幫助將是偉大的!

在此先感謝。

+0

檢查您的系統上是否有'grep'程序可用。因爲'grep -v'從輸入中打印所有不匹配的行。 – 2012-08-15 12:14:32

+0

[我想刪除包含某些字符串的行]的可能重複(http://stackoverflow.com/questions/11968998/i-want-to-remove-lines-that-c​​ontain-certain-string) – sloth 2012-08-16 11:02:52

回答

3
with open('data.txt') as f,open('out.txt') as f2: 
    for x in f: 
     if 'are' not in x: 
      f2.write(x.strip()+'\n') #strip the line first and then add a '\n', 
             #so now you'll not get a empty line between two lines 
+3

只需做f2 .WRITE(X)。新行字符已經是x的一部分。 strip()還會去除可能不需要的空白。另一個解決方法:打開('out.txt','w')。此外這個代碼需要python 2.7。 – 2012-08-15 03:49:35

3

與往常一樣。打開源文件,打開目標文件,只將需要從源文件複製到目標文件中的行,關閉這兩個文件,將目標文件重命名爲源文件。

相關問題