Python Forum
try/except for filename extensions?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
try/except for filename extensions?
#1
I have a program that works with .txt files that contain specifically formatted data. I need my program to evaluate whether the selected file is a .txt file and print an error message if an improper file type is selected. I've tried file.endswith(".txt") but I don't think my program is pulling the filename as a string, and I can't get try/except to work either. This is the beginning of my program:

import numpy as np
import peakutils
from peakutils.plot import plot as pplot
from matplotlib import pyplot
from matplotlib import mlab
import tkinter as tk
from tkinter import filedialog
from scipy import signal 
from scipy.signal import savgol_filter

root = tk.Tk()
root.withdraw()
root.attributes('-topmost',True)

file = filedialog.askopenfilename(parent=root)
#I need error handling for an incorrect file type

file = open(file).read().split('\n')
row1 = file[0].split(' ')
y = np.array(file[1:len(file)-1]).astype(np.float)
timeStep = float(row1[5])
x = [i for i in range(len(file)-2)]
x = np.array(x)
There are also a litany of errors that pop up if a .txt file with improperly formatted data is chosen, including ValueError, UnicodeDecodeError, and others. All of them should arise within the span of the code I have put here. I've been told before that I shouldn't leave a naked except, but if I only want a single error message to deal with all potential errors, do I really need to write out every conceivable error type in a series of except commands?
"Nobody really knows how to program, the pros Google too." -A Google Engineer
Reply
#2
askopenfilename can be restrict to open chosen file types.
Example:
from tkinter import Tk
from tkinter import filedialog

root = Tk()
try:
    root.filename = filedialog.askopenfilename(
                    initialdir='/', title='Select file',
                    filetypes=[('Text files','*.txt')]
                    )
    print(root.filename)
except(OSError,FileNotFoundError):
    print(f'Unable to find or open <{root.filename}>')
except Exception as error:
    print(f'An error occurred: <{error}>')
So (OSError,FileNotFoundError) may not even be needed,
but you see how more than one expedition can be in a tuple.

So if try to open file and get UnicodeDecodeError,
then exception can be alone if need a special message to user for that specific error.

except Exception as error: is an all in solution better that bare expect:
As it will give info about error that have occurred.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020