python如何删除文件里包含关键词的行

15次阅读

要把一个文件里的所有含有/local/server的行删除.

honglio

import shutil
with open('/path/to/file', 'r') as f:
    with open('/path/to/file.new', 'w') as g:
        for line in f.readlines():
            if '/local/server' not in line:             
                g.write(line)
shutil.move('/path/to/file.new', '/path/to/file')

cute

with open(out_file, 'w') as f:
    f.write(''.join([line for line in open(in_file).readlines() if '/local/server' not in line]))

其中in_file是需要处理的文件,out_file是处理后输出的文件。

G_will

1.每次读取一行
2.正则匹配(也就是把关键字做正则替换动作)
3.写入关闭

or

使用string的replace

output_file.write(input_file.read().replace(stext,rtext))

Yukir

说句题外话,如果你在Unix平台上的话,可以不用重新发明轮子。

grep -v '/local/server' filename

就可以解决问题了。(用sed也可以。)

万能Lambda

Another Python One Liner:

open("outfile", "w").write(''.join(map(lambda x: "/local/server" in x and "\n" or x, open("infile", "r"))))

felix021

命令行下直接上: sed -i '/keywords/d' files

当多个目录时,需要配合grep -rl 使用了.

eg:


# linux
sed -i '/keywords/d' `grep keywords -rl yourdir`

# mac
sed -i '' '/keywords/d' `grep keywords -rl yourdir`

vim下的话就: :g/keywords/d

mugbya

正文完