hexagon logo

Help with script to change text file

Hi everyone, I am still very much a novice with scripts but I have just worked on a very simple one to change the line in a text file.

This works perfectly for what I am trying to do, however I have to write the exact file name every time I want it to change the words, which is obviously slower than me going in and altering it by hand which is what I do now.

I am running this from excel by the way using a button.

Firstly I would like to know if what I want is possible. Secondly what I want is for me to be able to click a button in excel and it will make the required change to all the dmo files in a single folder without me having to change the file name.

So if I say this is the file path "S:\DMO Files from CMM" and it will search the folder and make the changes to all the files. Is this possible?

Basically I have no idea how to go about this at the moment so any help would be great.

Sub Button1_Click()

Const ForReading = 1

Const ForWriting = 2


Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.OpenTextFile("S:\DMO Files from CMM\LH Anodised Silver 02.02.2018 - 1.dmo", ForReading)


strText = objFile.ReadAll

objFile.Close

strNewText = Replace(strText, "FILNAM/'31862383.dmo'", "FILNAM/'31862383'")


Set objFile = objFSO.OpenTextFile("S:\DMO Files from CMM\LH Anodised Silver 02.02.2018 - 1.dmo", ForWriting)

objFile.WriteLine strNewText

objFile.Close


End Sub
Parents
  • I think this is what you're asking for, but written in Python since I suck at VB.
    Be very careful if you run this. It will run the replace function on every file in the srcfolder as well as in any subfolders.
    I always make a backup of the folder before I attempt any mass changes like this.
    import os
    srcfolder = r"S:\DMO Files from CMM"
    
    for root,dirs,files in os.walk(srcfolder):
      for filename in files:
        with open(os.path.join(root, filename), "r+") as file:
          filecontents = file.read().replace("FILNAM/'31862383.dmo'","FILNAM/'31862383'")
          file.seek(0)
          file.truncate()
          file.write(filecontents)


    To run it:
    Download and install Python 3.6.4 from here (Make sure you check the "Add Python 3.6 to PATH" checkbox when you install it.) I think you have to restart as well.
    Save the above code to a text file with a '.py' extension instead of '.txt'
    Double click it.
    Profit.
Reply Children
No Data