Nov-12-2017, 07:40 PM
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