Search code examples
pythonpython-ospython-mode

Which Module do I use In python to browse, Copy and paste Files in Directories


I want to add a function in my program that when called , opens a browsing window like ones that open when you click on browse to change directory location in a setup. I want it to let me browse through directories , select a file and when I select it, it has to move that file to a pre-decided location in my system. Is it possible ? And if yes , Which module of python should I study and use .


Solution

  • We can use pre built shutil library in python to do copy and move actions.

    import shutil
    
    original = 'Path/To/Folder'
    target = 'New/Path'
    
    # Copies Folder
    shutil.copy(original, target)
    
    # Moves Folder
    shutil.move(original, target)
    
    # Copies Complete Tree
    shutil.copytree(original, target)
    

    For getting a path by browsing it in file dialog we use prebuilt library named as tkinter like this:

    import tkinter
    
    # Returns the path to file opened
    tkinter.filedialog.askopenfile()
    tkinter.filedialog.askopenfiles()
    
    # Returns the path to folder opened
    tkinter.filedialog.askdirectory()