Search code examples
pythonjythonglobpython-rejython-2.5

Changing a folder in a path for writing using re and glob libraries


I have two directories: path/to/folder and path/to/otherfolder which both have several sub-directories inside them: path/to/folder/TEST1, path/to/folder/TEST2, path/to/otherfolder/TEST1, path/to/otherfolder/TEST2, etc.

I'm getting all the subdirectories in the root folder using folder_path = glob.glob('path/to/folder/*')

I then loop over each sub-directory to get all the files in them:

for folder in folder_path:
    file_path = glob.glob(folder + '\*')
    for files in file_path:
        new_path = files.replace('folder', 'otherfolder')
        with open(files, r) as f:
            with open(new_path, 'wb') as wf:
                do stuff

This isn't working though as no files are being written to. I thought about simply changing this line to files.replace('\\folder\\', '\\otherfolder\\') but I don't think this will work.

I'd like to use Python's re library if anyone has any ideas?


Solution

  • It looks like the problem is the glob pattern. Instead of:

        file_path = glob.glob(folder + '\*')
    

    can you try

        file_path = glob.glob(os.path.join(folder, '*'))
    

    ?

    This will require you to import os at the top of your file.


    There is also a syntax error here:

            with open(files, r) as f:
    

    Should be:

            with open(files, 'r') as f: