Menu

Find & Replace With Filename

2017-05-24
2017-05-24
  • Ashton Watts

    Ashton Watts - 2017-05-24

    Good eveing,

    hoping someone can help.

    I have a few thousand files that all have specific bits of texts that need to be replaced with the file name of that particular file. After a bit of searching, I think Python is the best was to do this but it isn't something i'm very familiar with so am using the nppp python plugin.

    Essentially, I have a directory (Y:\dataFiles) that contains all of the xml files that need editing, i was hoping to run a script to edit .xml in Y:\dataFiles and replace 'replaceData' with .xml

    this is what I have so far but get a syntax error on the *

    os.chdir('Y:\dataFiles')
    for f in *.xml; do
        editor.rereplace('replaceData', notepad.getCurrentFilename())
        notepad.save()
        notepad.close()
    done
    

    Thanks in advance,
    Ashton

     
  • CFrank

    CFrank - 2017-05-25

    This is not really python syntax ;-)

    import os
    
    os.chdir('Y:\dataFiles')
    list_of_files = [x for x in os.listdir('.') if x.endswith('.xml')]
    for file in list_of_files:
        notepad.open(file)
        editor.rereplace('replaceData', notepad.getCurrentFilename())
        notepad.save()
        notepad.close()    
    

    First you cahnge to the directory (as you already did)
    then you create a list of all files which end with .xml
    now iterate over that list and
    open it (otherwise you cannot use editor object)
    replace the data
    save and close it.

    Not tested but I assume it should do it. Maybe you wanna test first with a directory
    containing only one xml file and see the result.

    Cheers
    Claudia

     
  • Ashton Watts

    Ashton Watts - 2017-05-25

    Hi Claudia,

    Thanks very much for getting back to me, this worked perfectly except that it kept changing \ for \ in the path name. i got around this by doing
    os.chdir('Y:') os.chdir('dataFiles')

    Messy, but it worked.

    thanks again.
    Ashton

     
  • Sasumner

    Sasumner - 2017-05-26

    When you use \ inside of a string you need to double it.

    Example: os.chdir('Y:\\dataFiles')

     

    Last edit: Sasumner 2017-05-26

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.