2012-08-15 148 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

与往常一样。打开源文件,打开目标文件,只将需要从源文件复制到目标文件中的行,关闭这两个文件,将目标文件重命名为源文件。

相关问题