在 Python 中,当我循环遍历文件目录时,如何在根目录下输入一个文本文件并将与 re 匹配的字符串替换为 xxxxx

In Python, As Iam looping through a file directory how do enter a text file at the root and replace strings that match re with xxxxx

我想遍历包含许多文件的目录并在每个文本文件中追加字符串。我可以使用 re.findall 方法捕获字符串。我想在每个文本文件中用 xxxx 替换该字符串..

import os
import pandas as pd
import numpy as np
import re

start = os.getcwd()
for (root,dirs,files) in os.walk(start):
    if files.endswith('.txt'):
        keepfile = files
        with open(keepfiles,'a') as newFile:
            content = newFile.read()
            text1 = re.findall('name',content)
            text2 = re.findall(‘_serial..\w+’,content)
            ReplaceWith1= content .replace(text1,'xxxxxx')
            ReplaceWith2= text2.replace(‘text2,’ttttt’)

你可以这样做,但我会在你复制的目录中测试它以确保它符合你的规格,我认为它确实如此:

import os
from glob import glob
path = "/tmp/testchange"

f = glob(os.path.join(path,"*name*"))
n = []
for x in range(len(f)):
   n.append(f[x].replace('name', 'xxxxxx'))
for x in range(len(f)):
  os.rename(f[x], os.path.join(path, n[x]))

您的代码中遗漏了一些内容,但您可以试试这段代码。 主要变化是:

  1. w+ 模式打开文件以截断其内容。
  2. 更改了替换内容的顺序。
  3. 正在将所有内容写回 newFile

    import os
    import pandas as pd
    import numpy as np
    import re
    
    start = os.getcwd()
    for (root,dirs,files) in os.walk(start):
        if files.endswith('.txt'):
            keepfile = files
            with open(keepfiles,'w+') as newFile:
                content = newFile.read()
                text1 = re.findall('name',content)
                ReplacedWith1= content.replace(text1,'xxxxxx')
                text2 = re.findall(‘_serial..\w+’,ReplacedWith1)
                ReeplacedWith2= text2.replace(‘text2,’ttttt’)
                newFile.write(ReeplacedWith2)