How to check empty file path and valid file name?

Viewed 78

I am a beginner in python. I have some problems in my learning, I hope I can find the answer here.

  1. I cancel select file dialog and PyCham show file not found error.

    # importing openpyxl module
    import openpyxl as xl
    from openpyxl import Workbook
    from openpyxl.styles import Color, PatternFill, Font, Border
    from openpyxl.formatting.rule import Rule
    from openpyxl.styles.differential import DifferentialStyle
    
    # importing pandas module
    import pandas as pd
    from tkinter import *
    from tkinter import CENTER
    from tkinter import ttk
    from tkinter import filedialog
    from tkinter.messagebox import showinfo
    from tkinter import messagebox as msg
    from pandastable import Table
    from tkintertable import TableCanvas
    
    # importing get filename module
    import ntpath
    from pathlib import Path
    
    # importing numpy module
    import numpy as np
    
    
     def openFile():
          filepath = filedialog.askopenfilename(initialdir='\\Desktop',
                                                 title='Check Duplicate',
                                                 filetypes=(('Excel Files', '*.xlsx'),
                                                            ('All Files', '*.*')))    
    df = pd.read_excel(filepath)
    
    window = Tk()
    window.geometry('300x300')
    window.resizable(False, False)
    button_choose_file = ttk.Button(window, text='Choose File', command=openFile).pack(ipadx=50, ipady=10, expand=True)
    window.mainloop()
    
  2. Q1: How to use if, else to check that is a empty file path with pandas read?

  3. Q2: If my select excel filename is Student_2020_01_05.xlsx (Format: filename_yyyy_mm_dd.xlsx). How to if, else to check that is valid file name?

1 Answers

One method to address both questions is to write a helper function to perform the tests. If both tests pass, a True value is returned, otherwise False is returned.

Then, you can simply use the following statement:

if valid_file(fpath=filepath):
    df = pd.read_excel(filepath)

The file will only be read if:

  1. The filepath is not None (the file was chosen by the user and not cancelled.)
  2. The filepath exists.
  3. The filename meets the required convention.

Helper function:

This function first perfoms a test that fpath is not None (verifying a file was selected). Then, a True value is returned if the filepath exists and the filename meets the required naming convention.

import re

def valid_file(fpath: str) -> bool:
    """Verify a filename is valid and path exists."""
    if fpath is None:
        return False
    re_file = re.compile('[A-Z][a-z]+_\d{4}_\d{2}_\d{2}.xlsx')
    return os.path.exists(fpath) and re_file.match(os.path.basename(fpath)) is not None

Futher comments:

Here is an explanation of the regular expression (regex) pattern used to validate the file:

'[A-Z][a-z]+_\d{4}_\d{2}_\d{2}.xlsx'
  • Match a single upper case letter.
  • Match one or more lower case letters.
  • Match an underscore.
  • Match four digits followed by an underscore.
  • Match two digits followed by an underscore.
  • Match two digits.
  • Match '.xlsx' as the file extension.
Related