netcrsky 发表于 2016-01-02 04:29

Python 删除特定字符的行

A.txt文件有10万行。

只要行中出现 gmail 或者 aol 或者 yahoo 就删除这个行。

用Python怎么写,谢谢啦!

zhonghua7896321 发表于 2016-01-05 13:39

一个非常简单但很耗资源的办法,仅供参考

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()

netcrsky 发表于 2016-01-08 21:55

:D谢谢,已经足够用了。

bskay 发表于 2016-02-05 10:56

readlines()改为xreadlines()就不耗资源了

zhonghua7896321 发表于 2016-02-07 18:34

回复 4# bskay


    的确,迭代可以有效减少内存开销。
    另外推荐一种方式,那就是使用with语句来读写文件,一样可以达到控制资源消耗的目的。

一天睡三次 发表于 2016-02-17 14:48

新人受教了

ssfjhh 发表于 2016-02-18 13:56

规则太简单,就不用正则表达式了。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 = '')

一天睡三次 发表于 2016-02-19 10:47

回复 7# ssfjhh


    请问您的python版本号是多少?我在2.7.3上运行这个代码会出错。

ssfjhh 发表于 2016-02-19 12:03

一天睡三次 发表于 2016-02-19 10:47 static/image/common/back.gif
回复 7# ssfjhh




python3.5

zl624867243 发表于 2016-02-19 13:41

我也来一个#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]
查看完整版本: Python 删除特定字符的行