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

2024-07-05 07:39:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要列出txt文件,搜索和替换每个txt文件的文本只。你知道吗

需要搜索$$\d…其中\d代表数字1、2、3…..100。 需要替换为xxx。你知道吗

请让我知道这个python脚本。你知道吗

提前谢谢。你知道吗

-施里尼瓦斯

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

Tags: 文件theintxtforislineit
3条回答

你可以试试这个:

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

试试这个。你知道吗

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函数,而不是字符串。你知道吗

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,但它会忽略fileinput的主要功能。你知道吗

相关问题 更多 >