pythonshutil

Unexpected behaviour when re-organising directory (python, shutil)


I have a function that reorganises a directory of locally saved data, but its behaving in an unexpected way. There are 3 folders, current, previous and tma (two months ago) and with the function below I am expecting that it will delete the existing tma, rename current -> previous, previous -> tma and then re-create and populate (with another function) a current folder.

import os
import shutil

__PATH = os.getcwd()

def reorganise_directory():
    print(__PATH)
    destinations = ['current', 'previous', 'tma']
--->shutil.rmtree(os.path.join(__PATH, f'/data/{destinations[-1]}'))
    shutil.move(os.path.join(__PATH, f'/data/{destinations[1]}'), os.path.join(__PATH, f'/data/{destinations[-1]}'))
    shutil.move(os.path.join(__PATH, f'/data/{destinations[0]}'), os.path.join(__PATH, f'/data/{destinations[1]}'))
    return

This is the error I recieve:

enter image description here

It appears that for some reason, the __PATH variable, which prints out C:\dev\python\smog_usage_stats is being turned to just C:\ in the line indicated by an arrow. I'm not sure why?


Solution

  • Try to use it:

    import os
    import shutil
    
    __PATH = os.getcwd()
    
    def reorganise_directory():
        print(__PATH)
        destinations = ['current', 'previous', 'tma']
        # Change f"/data/{destinations[x]}" to "data", destinations[x]
        shutil.rmtree(os.path.join(__PATH, "data", destinations[-1]))
        shutil.move(os.path.join(__PATH, "data", destinations[1]), os.path.join(__PATH, "data", destinations[-1]))
        shutil.move(os.path.join(__PATH, "data", destinations[0]), os.path.join(__PATH, "data", destinations[1]))
        return
    

    Don't use Unix-like slashes on NT systems or backwards. It may cause unexpected behaviours + if you don't use slashes in 'os.path.join' (only names), you will have platform-indepedency, what would help to start your program, for example, on Linux or MacOS.