HS Banner
Back
How to open a text file in Python

Author: Admin 12/28/2025
Language: Python
Tags: python open file


Description:

Here's how to open a text file in Python.

Article:

from tkinter import filedialog

# Create filrgialg function
def select_file(window_title):
    # Hide the main Tkinter window (which would otherwise appear as an empty box)
    root = tk.Tk()
    root.withdraw()
    # Open the file selection dialog
    file_path = filedialog.askopenfilename(
        title=window_title,
        initialdir="/",  # Optional: start directory
        filetypes=(("Text files", "*.txt"), ("All files", "*.*"))  # Optional: file filters
    )
    # Destroy the hidden root window after selection
    root.destroy()
    # Return the selected file path (as a string)
    return file_path
    
# Select the file to read
selected_file = select_file("Select plain text list") # Enable to run the file dialog

with open(selected_file, 'r') as file:
	p = file.read().splitlines()
	
# Print file
print(type(p), p)



Back
Comments
Add Comment
There are no comments yet.