user122244
user122244

Reputation: 119

Ask a user to select folder to read the files in Python?

I have a script that I need to ask the user to select the folder where reside two subfolders that contain each one file that are needed to be read. Kind of giving their directory.

I was thinking about a pop up where they choose the folder. There is tkinter that is supposed to do it but I can't make it work. Maybe if the user puts the script file in that specific folder where the subfolders with the files are located, it would render searching the folder easier?? It would be nice to make it as easy as possible for the user.

The changes in this module have make it difficult to work with. What do you think?

from tkinter.filedialog import askdirectory
path=askdirectory()

I also did this where the comment suggests but it keeps running and nonthing is happening:

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

Upvotes: 6

Views: 39921

Answers (2)

t44
t44

Reputation: 21

Another way to do this is using promptlib. You may have to install it with pip install promptlib.

To use it:

import promptlib

prompter = promptlib.Files()

dir = prompter.dir()
file = prompter.file()

print(dir, '\n', file)

Upvotes: 2

Anil Sharma
Anil Sharma

Reputation: 69

Try following, worked for me.

from tkinter import Tk
from tkinter.filedialog import askdirectory
path = askdirectory(title='Select Folder') # shows dialog box and return the path
print(path)  

Upvotes: 6

Related Questions