Python 删除特定字符的行
A.txt文件有10万行。只要行中出现 gmail 或者 aol 或者 yahoo 就删除这个行。
用Python怎么写,谢谢啦! 一个非常简单但很耗资源的办法,仅供参考
import re
lines = []
f = open('A.txt')
for line in f.readlines():
ifnot re.search('gmail|aol|yahoo', line):
lines.append(line)
f.close()
f = open('A.txt', 'w')
f.writelines(lines)
f.close()
:D谢谢,已经足够用了。 readlines()改为xreadlines()就不耗资源了
回复 4# bskay
的确,迭代可以有效减少内存开销。
另外推荐一种方式,那就是使用with语句来读写文件,一样可以达到控制资源消耗的目的。 新人受教了 规则太简单,就不用正则表达式了。import fileinput
todelete = ['gmail', 'aol', 'yahoo']
with fileinput.input('A.txt', inplace = True) as f:
for line in f:
if all(string not in line for string in todelete):
print(line, end = '')
回复 7# ssfjhh
请问您的python版本号是多少?我在2.7.3上运行这个代码会出错。 一天睡三次 发表于 2016-02-19 10:47 static/image/common/back.gif
回复 7# ssfjhh
python3.5 我也来一个#coding:utf-8
import shutil
#读取文件
#print file('d:\\a.txt').read()
tt = ['gmail','yahoo']
with open('d:\\a.txt','r') as f:
with open ('d:\\a1.txt','w') as g:
for line in f.readlines():
if all(string not in line for string in tt) :
g.write(line)
shutil.move('d:\\a1.txt', 'd:\\a.txt')
页:
[1]