-1

I want to loop through a directory with many files and append strings within a each text file. I can capture the string with re.findall method. I want to replace that string with xxxx within each text file..

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

2 Answers2

0

There are couple of things missed in your code, but you can try this code. Main changes are:

  1. open the file in w+ mode to truncate its content.
  2. changed the order of replaced content.
  3. Writing eveerything back to 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)
    
Pratik
  • 1,351
  • 1
  • 20
  • 37
-1

You can do that with this, but i would test it in a directory you have duplicated to make sure it works to your specifications, which i think it does:

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]))
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
  • Glob has been known to miss files. So IAm trying to use os.walk. I am able to walk through the files but I know how to find the text. I just to replace the strings in each file. –  Nov 12 '19 at 07:28
  • Why do you think glob can miss files?? – tripleee Nov 12 '19 at 07:37
  • 1
    Are we trying to replace filename or the content of file? From OP's code it looks like we are trying to change the content – Pratik Nov 12 '19 at 07:50