Python открыть папку в проводнике windows

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:pathoffolder"') but I have no solution for

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:pathoffolder"')

but I have no solution for files.

Trilarion's user avatar

Trilarion

10.4k9 gold badges64 silver badges102 bronze badges

asked Nov 11, 2008 at 19:24

Kirill Titov's user avatar

Kirill TitovKirill Titov

1,9914 gold badges20 silver badges33 bronze badges

A nicer and safer 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 (for security reasons) and this solution may help other people.

answered Mar 7, 2018 at 19:40

Guillaume Lebreton's user avatar

6

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,', path])

answered Jun 21, 2018 at 9:56

ewerybody's user avatar

ewerybodyewerybody

1,33313 silver badges29 bronze badges

4

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)

answered Dec 2, 2014 at 13:51

user1767754's user avatar

user1767754user1767754

22.5k18 gold badges136 silver badges160 bronze badges

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()

answered Oct 18, 2018 at 19:48

MacNutter's user avatar

MacNutterMacNutter

1821 silver badge5 bronze badges

0

For anyone wondering how to use a variable in place of a direct file path. The code below will open explorer and highlight the file specified.

import subprocess
subprocess.Popen(f'explorer /select,{variableHere}')

The code below will just open the specified folder in explorer without highlighting any specific file.

import subprocess
subprocess.Popen(f'explorer "{variableHere}"')

Ive only tested on windows

answered Dec 15, 2020 at 15:57

Stephan Yazvinski's user avatar

1

Code To Open Folder In Explorer:

import os
import ctypes
SW_SHOWDEFAULT = 10
path_to_open = os.getenv('windir')
ctypes.windll.shell32.ShellExecuteW(0, "open", path_to_open, 0, 0, SW_SHOWDEFAULT)

answered Dec 6, 2021 at 6:27

Pixelsuft's user avatar

import subprocess
subprocess.Popen(r'explorer /open,"C:pathoffolderfile"')

I find that the explorer /open command will list the files in the directory.
When I used the /select command (as shown above), explorer opened the parent directory and had my directory highlighted.

answered Jul 6, 2022 at 18:17

RAllenAZ's user avatar

I’m in Python, and I have the path of a certain folder. I want to open it using the default folder explorer for that system. For example, if it’s a Windows computer, I want to use Explorer, if it’s Linux, I want to use Nautilus or whatever is the default there, if it’s Mac, I want to use Finder.

How can I do that?

Jace Browning's user avatar

asked Jul 8, 2011 at 22:41

Ram Rachum's user avatar

Ram RachumRam Rachum

81.5k82 gold badges230 silver badges370 bronze badges

1

I am surprised no one has mentioned using xdg-open for *nix which will work for both files and folders:

import os
import platform
import subprocess

def open_file(path):
    if platform.system() == "Windows":
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])

answered Apr 24, 2013 at 23:36

Cas's user avatar

5

You can use subprocess.

import subprocess
import sys

if sys.platform == 'darwin':
    def openFolder(path):
        subprocess.check_call(['open', '--', path])
elif sys.platform == 'linux2':
    def openFolder(path):
        subprocess.check_call(['xdg-open', '--', path])
elif sys.platform == 'win32':
    def openFolder(path):
        subprocess.check_call(['explorer', path])

answered Jul 8, 2011 at 22:46

Dietrich Epp's user avatar

Dietrich EppDietrich Epp

201k36 gold badges336 silver badges411 bronze badges

5

The following works on Macintosh.

import webbrowser
webbrowser.open('file:///Users/test/test_folder')

On GNU/Linux, use the absolute path of the folder. (Make sure the folder exists)

import webbrowser
webbrowser.open('/home/test/test_folder')

As pointed out in the other answer, it works on Windows, too.

answered Sep 13, 2012 at 13:21

punchagan's user avatar

punchaganpunchagan

5,4061 gold badge18 silver badges23 bronze badges

4

I think you may have to detect the operating system, and then launch the relevant file explorer accordingly.

This could come in userful for OSX’s Finder: Python «show in finder»

(The below only works for windows unfortunately)

import webbrowser as wb
wb.open('C:/path/to/folder')

This works on Windows. I assume it would work across other platforms. Can anyone confirm? Confirmed windows only :(

Community's user avatar

answered Jul 8, 2011 at 22:45

Acorn's user avatar

AcornAcorn

48k26 gold badges129 silver badges172 bronze badges

5

One approach to something like this is maybe to prioritize readability, and prepare the code in such a manner that extracting abstractions is easy. You could take advantage of python higher order functions capabilities and go along these lines, throwing an exception if the proper function assignment cannot be made when a specific platform is not supported.

import subprocess
import sys


class UnsupportedPlatformException(Exception):
    pass


def _show_file_darwin():
    subprocess.check_call(["open", "--", path])

def _show_file_linux():
    subprocess.check_call(["xdg-open", "--", path])

def _show_file_win32():
    subprocess.check_call(["explorer", "/select", path])

_show_file_func = {'darwin': _show_file_darwin, 
                   'linux': _show_file_linux,
                   'win32': _show_file_win32}

try:
    show_file = _show_file_func[sys.platform]
except KeyError:
    raise UnsupportedPlatformException


# then call show_file() as usual

answered Apr 8, 2019 at 12:49

Reblochon Masque's user avatar

Reblochon MasqueReblochon Masque

34.6k10 gold badges53 silver badges76 bronze badges

For Mac OS, you can use

import subprocess
subprocess.run["open", "your/path"])

answered Jan 10 at 3:33

bingtanghuluwa's user avatar

I’m in Python, and I have the path of a certain folder. I want to open it using the default folder explorer for that system. For example, if it’s a Windows computer, I want to use Explorer, if it’s Linux, I want to use Nautilus or whatever is the default there, if it’s Mac, I want to use Finder.

How can I do that?

Jace Browning's user avatar

asked Jul 8, 2011 at 22:41

Ram Rachum's user avatar

Ram RachumRam Rachum

81.5k82 gold badges230 silver badges370 bronze badges

1

I am surprised no one has mentioned using xdg-open for *nix which will work for both files and folders:

import os
import platform
import subprocess

def open_file(path):
    if platform.system() == "Windows":
        os.startfile(path)
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", path])
    else:
        subprocess.Popen(["xdg-open", path])

answered Apr 24, 2013 at 23:36

Cas's user avatar

5

You can use subprocess.

import subprocess
import sys

if sys.platform == 'darwin':
    def openFolder(path):
        subprocess.check_call(['open', '--', path])
elif sys.platform == 'linux2':
    def openFolder(path):
        subprocess.check_call(['xdg-open', '--', path])
elif sys.platform == 'win32':
    def openFolder(path):
        subprocess.check_call(['explorer', path])

answered Jul 8, 2011 at 22:46

Dietrich Epp's user avatar

Dietrich EppDietrich Epp

201k36 gold badges336 silver badges411 bronze badges

5

The following works on Macintosh.

import webbrowser
webbrowser.open('file:///Users/test/test_folder')

On GNU/Linux, use the absolute path of the folder. (Make sure the folder exists)

import webbrowser
webbrowser.open('/home/test/test_folder')

As pointed out in the other answer, it works on Windows, too.

answered Sep 13, 2012 at 13:21

punchagan's user avatar

punchaganpunchagan

5,4061 gold badge18 silver badges23 bronze badges

4

I think you may have to detect the operating system, and then launch the relevant file explorer accordingly.

This could come in userful for OSX’s Finder: Python «show in finder»

(The below only works for windows unfortunately)

import webbrowser as wb
wb.open('C:/path/to/folder')

This works on Windows. I assume it would work across other platforms. Can anyone confirm? Confirmed windows only :(

Community's user avatar

answered Jul 8, 2011 at 22:45

Acorn's user avatar

AcornAcorn

48k26 gold badges129 silver badges172 bronze badges

5

One approach to something like this is maybe to prioritize readability, and prepare the code in such a manner that extracting abstractions is easy. You could take advantage of python higher order functions capabilities and go along these lines, throwing an exception if the proper function assignment cannot be made when a specific platform is not supported.

import subprocess
import sys


class UnsupportedPlatformException(Exception):
    pass


def _show_file_darwin():
    subprocess.check_call(["open", "--", path])

def _show_file_linux():
    subprocess.check_call(["xdg-open", "--", path])

def _show_file_win32():
    subprocess.check_call(["explorer", "/select", path])

_show_file_func = {'darwin': _show_file_darwin, 
                   'linux': _show_file_linux,
                   'win32': _show_file_win32}

try:
    show_file = _show_file_func[sys.platform]
except KeyError:
    raise UnsupportedPlatformException


# then call show_file() as usual

answered Apr 8, 2019 at 12:49

Reblochon Masque's user avatar

Reblochon MasqueReblochon Masque

34.6k10 gold badges53 silver badges76 bronze badges

For Mac OS, you can use

import subprocess
subprocess.run["open", "your/path"])

answered Jan 10 at 3:33

bingtanghuluwa's user avatar

Я изучаю питон, и я немного застрял …

Это мой код:

# TESTING FILE
import os
import subprocess
from pathlib import Path


# VAR
name = 'my_random_dir'


# Main
path2 = str(Path(__file__).parent.absolute())
var = path2 + "/" + name 
print(var)
subprocess.Popen(r'explorer /select "{var}"')

Я хотел бы открыть каталог внутри сценария папки, который создается автоматически (это означает, что я не могу заранее знать имя этой папки, и мне нужно связать его с переменными)

Я пробовал такие вещи, как приведенный выше код, но я не нашел решения … есть ли способ открыть папку в проводнике Windows, если вы не знаете имя папки, и вам нужно его взять из переменных?

Этот сценарий запускает только проводник Windows и игнорирует мой путь … есть ли синтаксическая ошибка? Я плохо к этому подхожу?

1 ответ

Лучший ответ

Используйте этот скрипт

import os
path = "C:\Users\shafi\Desktop\PAPER"
path = os.path.realpath(path)
os.startfile(path)

И он открывает папку БУМАГА

Не забудьте использовать // вместо /


2

Sadaf Shafi
19 Окт 2020 в 05:30

Форум сайта python.su

  • Главная
  • Пользователи
  • Найти
  • Войти
  • Sign up
  • Вы не вошли.

Уведомления

Группа в Telegram: @pythonsu

  • Начало
  • » Python для новичков
  • » открыть папку через проводник..
    [RSS Feed]

#1 Март 13, 2009 16:52:32

goblin_maks

От:
Зарегистрирован: 2008-12-10
Сообщения: 110
Репутация:

+  0  -

Профиль  

Отправить e-mail  

открыть папку через проводник..

необходимо из скрипта открыть папку..так чтоб ее содержимое отображалось в стандартном виндовом проводнике..

Офлайн

  • Пожаловаться

#2 Март 13, 2009 17:38:15

asv13

От:
Зарегистрирован: 2007-01-22
Сообщения: 130
Репутация:

+  0  -

Профиль  

Отправить e-mail  

открыть папку через проводник..

Т.е. нужно вызвать из скрипта проводник — explorer “c:program Files”

Офлайн

  • Пожаловаться

#3 Март 13, 2009 17:50:17

igor.kaist

От:
Зарегистрирован: 2007-11-12
Сообщения: 1879
Репутация:

+  3  -

Профиль  

Отправить e-mail  

открыть папку через проводник..

import subprocess
subprocess.Popen('explorer "%s"'%(PATH))

Офлайн

  • Пожаловаться

#4 Дек. 8, 2016 16:15:32

IceIsNice

Зарегистрирован: 2016-11-14
Сообщения: 17
Репутация:

+  0  -

Профиль  

Отправить e-mail  

открыть папку через проводник..

не стал заводить новую тему, у меня такой вопрос, как вызвать проводник и через проводник указать путь к файлу. Такое окно есть в любой программе,Ctrl+O если нажать оно появляется.

Офлайн

  • Пожаловаться

#5 Дек. 8, 2016 16:31:26

Shaman

Зарегистрирован: 2013-03-15
Сообщения: 1369
Репутация:

+  88  -

Профиль  

Отправить e-mail  

открыть папку через проводник..

Например http://python.su/forum/topic/21507/

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » открыть папку через проводник..[RSS Feed]

Board footer

Перейти

Модераторировать

Powered by DjangoBB

Lo-Fi Version

Понравилась статья? Поделить с друзьями:
  • Python отказано в доступе windows 10
  • Python обновить до последней версии windows
  • Python не является внутренней или внешней командой windows 10
  • Python не устанавливается windows 7 setup failed
  • Python не устанавливается windows 7 service pack 1 установлен