Python删除目标词所在行的数据怎么操作,python目标词,要把一个文件里的所有含有
Python删除目标词所在行的数据怎么操作,python目标词,要把一个文件里的所有含有
要把一个文件里的所有含有/local/server的行删除.
1.每次读取一行
2.正则匹配(也就是把关键字做正则替换动作)
3.写入关闭
or
使用string的replace
output_file.write(input_file.read().replace(stext,rtext))
说句题外话,如果你在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"))))
import shutilwith 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是处理后输出的文件。
编橙之家文章,
相关内容
- Python类变量与实例变量有何不同及使用方法请大家说说
- python numpy fromfunction()调用我的理解对不对,numpyfromfun
- 想用python开发一个查找附近人及商圈的程序,求思路,
- python使用pickle来直接序列化requests模块session.cookies,,
- 求大家帮解一道关于python分割的算法题,python算法,罗列
- Python 大牛解释下列表推导的疑惑,python大牛,关于Pyth
- 通过brew安装了python2.X和python3.X,python3没有自带pip,p
- pycharm编辑器‘�û�δ��这种乱码,需要转码还是怎么
- 求好的gevent开源项目来练习,gevent开源项目练习,有没有
- 完成python字典取值操作原理及效率程度是什么,python字
评论关闭