python如何删除文件里包含关键词的行
迷茫
迷茫 2017-04-17 11:07:23
[Python讨论组]

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(6)
黄舟
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')
巴扎黑
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是处理后输出的文件。

伊谢尔伦

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

or

使用string的replace

output_file.write(input_file.read().replace(stext,rtext))
PHP中文网

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

grep -v '/local/server' filename

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

高洛峰

Another Python One Liner:

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

命令行下直接上: 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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号