Python:在文件I / O中过滤

时间:2013-11-24 20:48:47

标签: python file-io

我正试图从文档中取出字符串“a”和“b”。这是我正在做的但是它不起作用因为我不能在列表中使用replace。

def filter_ab(filename):
    fileRef=open(filename)
    file_list=fileRef.readlines()
    filter="ab"
    for k in file_list:
        for j in k:
        if j in filter:
          file_list=file_list.replace(j,"")

3 个答案:

答案 0 :(得分:2)

你能用这样的东西:

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('a', '').replace('b', ''))
f1.close()
f2.close()

答案 1 :(得分:0)

请使用:

def filter_ab(filename):
    lines = []
    with open(filename, "r") as fh:
        for line in fh.readlines():
            line = line.replace("a", "")
            line = line.replace("b", "")
            lines.append(line)
    with open(filename, "w") as fh:
        for line in lines:
            fh.write(line)

答案 2 :(得分:0)

str.translate对于像这样的事情实际上非常方便

with open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2:
  for line in f1:
      f2.write(line.translate(None, 'ab'))