3

Right now, I have this line in my code to hard-code the directory path

dir_path = '/home/user/pywork'

but I would rather let the user select it herself using a construct similar to R's scan(choose.files()).

How do I go about it?

Thanks,

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
nobo
  • 125
  • 1
  • 2
  • 7
  • asking directory path using a dialog box requires GUI programming. If your application runs in terminal you can use raw_input function. – thavan Jun 06 '12 at 13:08
  • can you who me how to this this with raw_input, i'm still fairly ignorant in matters Python. take into account that i'm inexcusably work on windows. – nobo Jun 06 '12 at 15:08
  • dir_path = raw_input("Enter directory path: ") - this will ask the user to enter directory path and the entered path will be saved in dir_path variable. – thavan Jun 06 '12 at 15:55

1 Answers1

8

One option I found after a quick google (python open directory dialog box) is to use TKinter:

import Tkinter, tkFileDialog
root = Tkinter.Tk()
dirname = tkFileDialog.askdirectory(parent=root, initialdir="/",
                                    title='Please select a directory')

I found the information here.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • See also http://stackoverflow.com/questions/5430272/open-file-with-python-dirselector – Paul Hiemstra Jun 06 '12 at 13:33
  • thanks a lot, it will probably solve the issue, i still have to figure out how to implement on python32, since i understand some things have changed. thanks for the useful info! – nobo Jun 06 '12 at 15:06
  • This is the only solution I know of for users who have CLI phobia - but is there any lighter weight version to include for a 10 line script when compiling? Most of my scripts are 40 lines or less but become 11MB when adding the one line for a user to select a file. – Marc Maxmeister Sep 27 '12 at 21:34
  • You can use `raw_input`, for more details see the comments to the question. – Paul Hiemstra Sep 27 '12 at 21:44
  • it fails with Tkinter but seems to work with tkinter ... also the dialog no longer works: https://docs.python.org/3/library/dialog.html#module-tkinter.filedialog – ProsperousHeart Feb 25 '22 at 14:52