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

The filedialog module in Tkinter provides built-in functions for displaying file and folder selection dialogs. While filedialog.askopenfilename() opens individual files, you can use filedialog.askdirectory() to let users select entire folders and read multiple files.

Selecting a Single File

The basic approach uses askopenfilename() to browse and select a file −

import tkinter as tk
from tkinter import filedialog

# Create window
root = tk.Tk()
root.withdraw()  # Hide the main window

# Open file dialog
filepath = filedialog.askopenfilename(
    title="Select a text file",
    filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
)

if filepath:
    with open(filepath, 'r') as file:
        content = file.read()
        print(f"File: {filepath}")
        print(f"Content preview: {content[:100]}...")
else:
    print("No file selected")
File: /path/to/selected/file.txt
Content preview: This is the beginning of the file content that was selected by the user...

Selecting a Folder to Read Multiple Files

Use askdirectory() to select a folder and process all files within it −

import tkinter as tk
from tkinter import filedialog
import os

# Create window
root = tk.Tk()
root.withdraw()  # Hide the main window

# Open folder dialog
folder_path = filedialog.askdirectory(title="Select a folder")

if folder_path:
    print(f"Selected folder: {folder_path}")
    
    # List all files in the folder
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        
        # Process only text files
        if filename.endswith('.txt'):
            try:
                with open(file_path, 'r') as file:
                    content = file.read()
                    print(f"\n--- {filename} ---")
                    print(f"Characters: {len(content)}")
            except Exception as e:
                print(f"Error reading {filename}: {e}")
else:
    print("No folder selected")
Selected folder: /path/to/selected/folder

--- file1.txt ---
Characters: 245

--- file2.txt ---
Characters: 189

GUI Application with File Selection

Here's a complete GUI application that combines both file and folder selection −

import tkinter as tk
from tkinter import filedialog, messagebox
import os

class FileReaderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("File Reader")
        self.root.geometry("600x400")
        
        # Create buttons
        tk.Button(root, text="Select File", command=self.select_file, 
                 font=('Arial', 12)).pack(pady=10)
        
        tk.Button(root, text="Select Folder", command=self.select_folder,
                 font=('Arial', 12)).pack(pady=10)
        
        # Text area to display content
        self.text_area = tk.Text(root, height=20, width=70)
        self.text_area.pack(pady=10, padx=10)
        
    def select_file(self):
        filepath = filedialog.askopenfilename(
            title="Select a file",
            filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
        )
        
        if filepath:
            try:
                with open(filepath, 'r') as file:
                    content = file.read()
                    self.text_area.delete(1.0, tk.END)
                    self.text_area.insert(1.0, f"File: {os.path.basename(filepath)}\n\n{content}")
            except Exception as e:
                messagebox.showerror("Error", f"Cannot read file: {e}")
    
    def select_folder(self):
        folder_path = filedialog.askdirectory(title="Select a folder")
        
        if folder_path:
            self.text_area.delete(1.0, tk.END)
            self.text_area.insert(1.0, f"Folder: {folder_path}\n\n")
            
            txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
            
            if txt_files:
                self.text_area.insert(tk.END, f"Found {len(txt_files)} text files:\n")
                for filename in txt_files:
                    self.text_area.insert(tk.END, f"? {filename}\n")
            else:
                self.text_area.insert(tk.END, "No text files found in this folder.")

# Create and run the application
if __name__ == "__main__":
    root = tk.Tk()
    app = FileReaderApp(root)
    root.mainloop()

Key Methods Comparison

Method Purpose Return Value
askopenfilename() Select single file File path string
askdirectory() Select folder Folder path string
askopenfilenames() Select multiple files Tuple of file paths

Conclusion

Use filedialog.askdirectory() to let users select folders for batch file processing. Combine with os.listdir() and file filtering to read specific file types from the selected directory.

Updated on: 2026-03-26T18:55:25+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements