Search code examples
filecopypysimplegui

how to copy file from directory to another using shutil in python


below code always gives me key error of values['-FOUT-'], I need to copy file from one directory to another with different name...values['-FOUT-'] is a key from Pysimplegui to get output directory path, can anyone please tell me what I'm doing wrong? note that if i put a normal string path in quotes it works but I wish to use key path from Pysimplegui , thanks.

shutil.copy2(r'.[PARS] Template Directory\PAR\test.xlsx', os.path.join(str(values['-FOUT-']),"file.xlsx"))


Solution

  • Following code demo the way how to get the new path by user selecting the folder, then you can call shutil.copy2(src, dst, *, follow_symlinks=True) to copy the file src to the file or directory dst.

    import os
    import PySimpleGUI as sg
    
    filename = "file.xlsx"
    
    layout = [
        [sg.Input(disabled=True, enable_events=True, key='-FOUT-'), sg.FolderBrowse()],
        [sg.Text(expand_x=True, key='Path')],
    ]
    window = sg.Window("Title", layout)
    
    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event == '-FOUT-':
            path = os.path.join(values['-FOUT-'], filename)
            window['Path'].update(f'Path: {repr(path)}')
    
    window.close()
    

    enter image description here