Choosing a file in Python with simple Dialog
Asked Answered
V

11

190

I would like to get file path as input in my Python console application.

Currently I can only ask for full path as an input in the console.

Is there a way to trigger a simple user interface where users can select file instead of typing the full path?

Valdis answered 26/8, 2010 at 21:13 Comment(1)
Good question. I was just looking for this. I upvoted it. Thanks!Blastoderm
T
286

How about using tkinter?

from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

Done!

Tepper answered 26/8, 2010 at 21:22 Comment(8)
I got TypeError: 'module' object is not callable on Tk().withdraw() - any ideas?Brina
I had to do root = Tk.Tk() then root.withdraw(). Now the open file dialog window does not close however.Brina
Using Python 3.x and I believe "Tkinter" is actually supposed to be all lowercase, "tkinter".Goodfellowship
@Goodfellowship yes, it was changed from "Tkinter" to "tkinter" for Python3Isabea
Is there any way to allow only certain types of files? for eg. I want the user to select image files onlyChinachinaberry
@ShantanuShinde I think this may work: filename = askopenfilename(filetypes=[("Image files", "*.png"), ("All Files", "*.*")])Ishmael
@Tepper Awesome. This work perfect for me. I did not wanted to do a whole GUI just for selecting a file purposeBlastoderm
Py3 code doesn't work. See @Sainath Reddy at the bottom here.Kobold
C
110

Python 3.x version of Etaoin's answer for completeness:

from tkinter.filedialog import askopenfilename
filename = askopenfilename()
Capelin answered 26/8, 2010 at 21:43 Comment(7)
For total parallelism, should probably also have import tkinter + tkinter.Tk().withdraw().Florence
this does not work for me (on Mac, Python 3.6.6) The GUI window opens but you cannot close it and you get beachball of deathTrehalose
same here. the file dialog won't closeOrris
this code is the exact same as the accepted answer but incomplete.Luffa
On Mac 10.14.6, this opened the File finder then it just crashed the entire system :(Hutcherson
This code crashes Jupyter Notebook v6.1.5 on Windows 10.Linsk
How would I then read this file path into a pd.read_excel() @StefanoPalazzo?Larisa
D
45

With EasyGui:

import easygui
print(easygui.fileopenbox())

To install:

pip install easygui

Demo:

import easygui
easygui.egdemo()
Dendrite answered 26/8, 2010 at 21:37 Comment(7)
This is the best solution so far. The main reason is that easygui is a pip package and easy to installCement
On Mac OSX 10.14.5, python 3.6.7, easygui 0.98.1 I get a horrible crash when I try this. Not recommended.Franklyn
Why am I getting invalid syntax error for print easygui.diropenbox()?Fireproofing
@Fireproofing #827448 ?Dendrite
@ChristopherBarber same with 10.14.6. Python just keeps quitting.Hutcherson
This appears to be for Python 2 as easygui attempts to import Tkinter instead of tkinterLowther
it makes python 3.9 crash on OSX 10.11.6Bloch
C
14

In Python 2 use the tkFileDialog module.

import tkFileDialog

tkFileDialog.askopenfilename()

In Python 3 use the tkinter.filedialog module.

import tkinter.filedialog

tkinter.filedialog.askopenfilename()
Chickaree answered 26/8, 2010 at 21:21 Comment(1)
It is not part of standard installation in Python 3.Thales
N
8

This worked for me

Reference : https://www.youtube.com/watch?v=H71ts4XxWYU

import  tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
Nonessential answered 13/6, 2021 at 5:21 Comment(2)
How would I then take this file path and put it into a pandas data frame (if the file was, say, from excel) pd.read_excel(r'file_path') does not work @SainathReddyLarisa
If you print out file_path you will see that it contains forward slashes instead of backwards slashes. Therefore, pandas can handle it across platforms (e.g. Windows and Linux). pd.read_excel(file_path) is all you need.Hydrosphere
M
7

The suggested root.withdraw() (also here) hides the window instead of deleting it, and was causing problems when using interactive console in VS Code ("duplicate execution" error).

Below two snippets to return the file path in "Open" or "Save As" (python 3 on Windows):

import tkinter as tk
from tkinter import filedialog

filetypes = (
    ('Text files', '*.TXT'),
    ('All files', '*.*'),
)

# open-file dialog
root = tk.Tk()
filename = tk.filedialog.askopenfilename(
    title='Select a file...',
    filetypes=filetypes,
)
root.destroy()
print(filename)

# save-as dialog
root = tk.Tk()
filename = tk.filedialog.asksaveasfilename(
    title='Save as...',
    filetypes=filetypes,
    defaultextension='.txt'
)
root.destroy()
print(filename)
# filename == 'path/to/myfilename.txt' if you type 'myfilename'
# filename == 'path/to/myfilename.abc' if you type 'myfilename.abc'
Myxomycete answered 15/8, 2021 at 0:2 Comment(1)
On a Mac in Python 3.10.1 with Tcl/Tk version 8.6 I had to use a list of tuples to not get an error: filetypes = [('Text files', '*.TXT'),('All files', '*.*')] (note the square brackets). With a tuple of tuples (normal brackets instead of square ones) as in the example above I received s = master.tk.call(self.command, *master._options(self.options)) _tkinter.TclError: bad Macintosh file type "files" (but note that I used a different file type than in the example, and only a single file type).Deleterious
G
5

Another option to consider is Zenity: http://freecode.com/projects/zenity.

I had a situation where I was developing a Python server application (no GUI component) and hence didn't want to introduce a dependency on any python GUI toolkits, but I wanted some of my debug scripts to be parameterized by input files and wanted to visually prompt the user for a file if they didn't specify one on the command line. Zenity was a perfect fit. To achieve this, invoke "zenity --file-selection" using the subprocess module and capture the stdout. Of course this solution isn't Python-specific.

Zenity supports multiple platforms and happened to already be installed on our dev servers so it facilitated our debugging/development without introducing an unwanted dependency.

Gooseherd answered 22/5, 2013 at 19:46 Comment(0)
D
5

I obtained much better results with wxPython than tkinter, as suggested in this answer to a later duplicate question:

https://stackoverflow.com/a/9319832

The wxPython version produced the file dialog that looked the same as the open file dialog from just about any other application on my OpenSUSE Tumbleweed installation with the xfce desktop, whereas tkinter produced something cramped and hard to read with an unfamiliar side-scrolling interface.

Dichlorodiphenyltrichloroethane answered 23/4, 2020 at 0:49 Comment(0)
C
3

Using Plyer you can get a native file picker on Windows, macOS, Linux, and even Android.

import plyer

plyer.filechooser.open_file()

There are two other methods, choose_dir and save_file. See details in the docs here.

Corking answered 30/9, 2021 at 13:24 Comment(1)
This raises a NotImplemented error!Jhansi
M
2

Here is a simple function to show a file chooser right in the terminal window. This method supports selecting multiple files or directories. This has the added benefit of running even in an environment where GUI is not supported.

from os.path import join,isdir
from pathlib import Path
from enquiries import choose,confirm

def dir_chooser(c_dir=getcwd(),selected_dirs=None,multiple=True) :
    '''
        This function shows a file chooser to select single or
        multiple directories.
    '''
    selected_dirs = selected_dirs if selected_dirs else set([])

    dirs = { item for item in listdir(c_dir) if isdir(join(c_dir, item)) }
    dirs = { item for item in dirs if join(c_dir,item) not in selected_dirs and item[0] != "." } # Remove item[0] != "." if you want to show hidde

    options = [ "Select This directory" ]
    options.extend(dirs)
    options.append("⬅")

    info = f"You have selected : \n {','.join(selected_dirs)} \n" if len(selected_dirs) > 0 else "\n"
    choise = choose(f"{info}You are in {c_dir}", options)

    if choise == options[0] :
        selected_dirs.add(c_dir)

        if multiple and confirm("Do you want to select more folders?") :
            return get_folders(Path(c_dir).parent,selected_dirs,multiple)

        return selected_dirs

    if choise == options[-1] :
        return get_folders(Path(c_dir).parent,selected_dirs,multiple)

    return get_folders(join(c_dir,choise),selected_dirs,multiple)

To install enquiers do,

pip install enquiries

Middleoftheroader answered 7/3, 2021 at 13:36 Comment(1)
unfortunately, enquiries 0.2.0 requires click<8.0.0,>=7.1.2 but many other things requre >=0.8Headstrong
A
0

I resolved all problem related to from tkinter import * from tkinter import filedialog

by just migrating from pycharm IDE to visual studio code IDE and every problem is solved.

Abiotic answered 12/7, 2021 at 12:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.