Python: Get a list of selected files in Explorer (WIndows 7)

前端 未结 4 1904
谎友^
谎友^ 2020-12-21 05:48

At work I can select multiple .xlsx files, and right clicking on one file will give me the option of combining the files to make a .pdf. Now I want to use the same functiona

4条回答
  •  被撕碎了的回忆
    2020-12-21 06:16

    Edit: Doesn't work yet, at least when using context menu

    I found a partial solution here. However it doesn't work if Internet Explorer is open (how do I detect this?). Also, if multiple instances of Windows Explorer is open, the selected files in all windows are counted. I added a check for this.

    import win32com.client as win32
    import os
    import win32ui
    
    
    def explorer_fileselection():
        working_dir = os.getcwd()
    
        clsid = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' #Valid for IE as well!
        shellwindows = win32.Dispatch(clsid)
    
        files = []
        try:
            for window in range(shellwindows.Count):
                window_URL = shellwindows[window].LocationURL
                window_dir = window_URL.split("///")[1].replace("/", "\\")
                if window_dir == working_dir:
                    selected_files = shellwindows[window].Document.SelectedItems()
                    for file in range(selected_files.Count):
                        files.append(selected_files.Item(file).Path)
        except:   #Ugh, need a better way to handle this one
            win32ui.MessageBox("Close IE!", "Error")
        del shellwindows
    
        return files
    
    
    print(*explorer_fileselection(), sep="\n")
    
    --- prints the selected files:
    
    C:\Users\oe\Python\ssa\util\test3.docx
    C:\Users\oe\Python\ssa\util\__init__.py
    C:\Users\oe\Python\ssa\util\explorer_filer.py
    C:\Users\oe\Python\ssa\util\test1.xlsx
    C:\Users\oe\Python\ssa\util\test2.xls
    

    I think I will add a *valid_ext parameter to the function, so I can do calls like explorer_fileselection("xlsx", "xls") to get Excel-files only.

提交回复
热议问题