Keywords: Python, File read, File type, text files, word files, PDF files, dialog box, tkinter package
Here is a sample Python code that asks the user to enter a file path and checks the file extension to determine if it's a .txt, .docx, or .pdf file.
It uses the os.path.splitext() method to split the file path into a filename and extension, and then compares the extension to a list of supported file types.
To open a file dialog box and retrieve the selected file path we can use the tkinter library in Python.
It then checks the file extension as before to determine if it's a .txt, .docx, or .pdf file.
import os
import tkinter as tk
from tkinter import filedialog
# list of supported file types
supported_extensions = ['.txt', '.docx', '.pdf']
# create tkinter window (it will be hidden)
root = tk.Tk()
root.withdraw()
# open file dialog box and retrieve selected file path
file_path = filedialog.askopenfilename()
# split file path into filename and extension
file_name, file_extension = os.path.splitext(file_path)
# check if extension is in the list of supported file types
if file_extension in supported_extensions:
print("File type is supported")
else:
print("File type is not supported")
When you run the above code using Python compiler, a dialog box will open where you can select a file.
After selecting a file, the code will print a message indicating if the file type is supported or not.
You can modify the code to perform any actions you want based on the file type, such as reading the contents of a .txt file or using a library like PyPDF2 to extract text from a .pdf file.