开发者社区> 问答> 正文

使用pandas pd.Excel文件和用户输入的文件夹路径和文件名

我正在使用以下pd.ExcelFile来打开和解析文件,但目前仅在一个字符串中包含实际的文件夹路径和文件名。

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')

问题来源stackoverflow

展开
收起
is大龙 2020-03-20 19:56:53 1176 0
1 条回答
写回答
取消 提交回答
  • 使用Pathlibos并且pandas和一些功能。

    您需要的关键功能之一是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
    
    

    回答来源stackoverflow

    2020-03-20 20:01:50
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
中文:即学即用的Pandas入门与时间序列分析 立即下载
即学即用的Pandas入门与时间序列分析 立即下载
低代码开发师(初级)实战教程 立即下载