Open explorer on a file

孤者浪人 提交于 2019-11-26 08:49:49

问题


In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:

import subprocess
subprocess.Popen(\'explorer \"C:\\path\\of\\folder\"\')

but I have no solution for files.


回答1:


From Geoff Chappell's The Windows Explorer Command Line

import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')



回答2:


A nicer and securer solution (only in Windows unfortunately) is os.startfile().

When it's given a folder instead of a file, it will open Explorer.

Im aware that i do not completely answer the question since its not selecting a file, but using subprocess is always kind of a bad idea and this solution may help other people.




回答3:


For some reason, on windows 7 it always opens the users Path, for me following worked out:

import subprocess
subprocess.call("explorer C:\\temp\\yourpath", shell=True)



回答4:


Alternatively, you could use the fileopenbox module of EasyGUI to open the file explorer for the user to click through and then select a file (returning the full filepath).

import easygui
file = easygui.fileopenbox()



回答5:


As explorer could be overridden it would be a little safer to point to the executable directly. (just had to be schooled on this too)

And while you're at it: use Python 3s current subprocess API: run()

import os
import subprocess
FILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe')

def explore(path):
    # explorer would choke on forward slashes
    path = os.path.normpath(path)

    if os.path.isdir(path):
        subprocess.run([FILEBROWSER_PATH, path])
    elif os.path.isfile(path):
        subprocess.run([FILEBROWSER_PATH, '/select,', os.path.normpath(path)])


来源:https://stackoverflow.com/questions/281888/open-explorer-on-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!