搜索从python中的.txt文件数替换字符串

时间:2017-08-16 04:02:29

标签: python python-2.7 python-3.x

目录中有多个文件,扩展名为.txt,.dox,.qcr等。

我需要列出txt文件,搜索&仅替换每个txt文件中的文本。

需要搜索$$ \ d ...其中\ d代表数字1,2,3 ..... 100。 需要替换为xxx。

请让我知道这个python脚本。

提前感谢。

-Shrinivas

#created following script, it works for single txt files, but it is not working for txt files more than one lies in directory。         -----

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

#following code is not working, i expect to list out the files start #with "um_*.txt", open the file & replace the "$$\d" with replaceAll function.

for um_file in glob.glob('*.txt'):
    t = open(um_file, 'r')
    replaceAll("t.read","$$\d","xxx")
    t.close()

3 个答案:

答案 0 :(得分:0)

试试这个。

import re
def replaceAll(file,searchExp,replaceExp):
    for line in file.readlines():  
        try:  
            line = line.replace(re.findall(searchExp,line)[0],replaceExp)
        except:  
            pass
        sys.stdout.write(line)

#following code is not working, i expect to list out the files start #with "um_*.txt", open the file & replace the "$$\d" with replaceAll function.

for um_file in glob.glob('*.txt'):
    t = open(um_file, 'r')
    replaceAll(t,"\d+","xxx")
    t.close()

这里我们将文件处理程序发送到replaceAll函数而不是字符串。

答案 1 :(得分:0)

fileinput.input(...)应该处理一堆文件,并且必须以相应的fileinput.close()结束。因此,您可以在一个电话中处理所有内容:

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=True):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        dummy = sys.stdout.write(line)      # to avoid a possible output of the size
    fileinput.close()                       # to orderly close everythin


replaceAll(glob.glob('*.txt'), "$$\d","xxx")

或在处理每个文件后始终关闭fileinput,但它忽略了主文件输入功能。

答案 2 :(得分:0)

你可以试试这个:

import os
import re

the_files = [i for i in os.listdir("foldername") if i.endswith("txt")]

for file in the_files:
    new_data = re.sub("\d+", "xxx", open(file).read())
    final_file = open(file, 'w')
    final_file.write(new_data)
    final_file.close()