【问题标题】:Using pandas pd.Excel File with user input for folder path and filename将 pandas pd.Excel 文件与用户输入的文件夹路径和文件名一起使用
【发布时间】:2020-07-01 10:24:43
【问题描述】:

我正在使用 pd.ExcelFile 如下打开和解析文件,但目前只有 actual 文件夹路径和文件名在一个字符串中。

wb = pd.ExcelFile(folder_path+filename)

我想把它放到一个函数中,要求用户提供路径和文件名并处理无效输入。我开始了类似下面的操作,但似乎无论如何都不会在函数内部生成错误,而且我不确定如何说“虽然 wb 不是有效的东西”继续提示输入文件路径,直到我们得到一个有效的路径?

def Load_Parse():
    folder_path = input('\nEnter the path to the qry_T spreadsheet here (include slashes at the start and at the end): ')
    filename = input('\nEnter the name of the spreadsheet to be used here: ')
    sheetname = input('\nEnter the sheet containing the data here, including the extension (e.g. "qry_Trajectory 2019.xlsx": ')
    try:
        wb = pd.ExcelFile(folder_path+filename)
    except FileNotFoundError:

有什么想法吗?

然后我将使用我希望的类似方法解析文件:

df = wb.parse('filename')

【问题讨论】:

    标签: python-3.x pandas input while-loop


    【解决方案1】:

    使用Pathlibospandas 以及一些函数。

    您需要的关键功能之一是while True,它会一直执行代码块,直到它为真并且您启动break

    随意编辑您自己的规范。

    模块

    from pathlib import Path
    import os
    import pandas as pd
    from xlrd import XLRDError
    

    在行动

    df = load_parser()
    
    out:
    #Hello Umar.Hussain please enter a valid target directory
    #C:\Users\UmarH\Files
    #1 excels_0
    #2 excels_1
    #Choose a number between 1 and 2
    1
    #Your Choice is excels_0.xlsx
    #Choose a Sheet - Lists all sheets
    'Sheet1'
    # returns dataframe
    

    主要功能

    def load_parser():
    
        user = os.getlogin()
    
        print(f"Hello {user} please enter a valid target directory") 
        cmd = input('')
    
        p = file_tester(cmd,file_type='path')
        print("Please select a number from the following file")
        target_file = create_excel_dict(p)
        target_df = enumerate_sheets(target_file)
    
    
    
        return target_df
    

    辅助函数

    def file_tester(string_path, file_type="path"):
        path = Path(string_path)
    
        while True:
            if path.is_dir():
                break
            else:
                cmd = input(f"Please Enter a Valid {file_type}")
                path = Path(cmd)
    
        return path
    
    
    def create_excel_dict(target_path):
        xlsx_dict = {i: x for i, x in enumerate(target_path.glob('*.xlsx'), 1)}
    
        for k,v in xlsx_dict.items():
            print(k,v.stem)
    
        rng = [i for i in xlsx_dict.keys()]
    
        file_choice = input(f'Choose a number between {rng[0]} and {rng[-1]}')
    
        while True:
            try:
                file_choice = int(file_choice)
                print(f"Your Choice is {xlsx_dict[file_choice]}")
                break
            except KeyError:
                file_choice = input(f'Choose a number between {rng[0]} and {rng[-1]}')
    
        return xlsx_dict[file_choice]
    
    def enumerate_sheets(target_file):
    
        xl = pd.ExcelFile(target_file)
    
        for sheet in xl.sheet_names:
            print(sheet)
        target_sheet = input("Please Type Your sheet name")
    
        while True:
            try:
                df = pd.read_excel(xl,sheet_name=target_sheet)
                break
            except XLRDError:
                target_sheet = input("Please enter a sheet from above.")
    
        return df
    

    【讨论】:

    • 我花了很尴尬的时间才得到这个(最后复制并粘贴到我这样做了),但这正是我所需要的,并且非常清楚地列出了。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2012-08-26
    • 2012-03-30
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多