如何使用 glob 查找文件,创建文件的嵌套字典,然后将文件显示给用户以供选择?

问题描述 投票:0回答:0

基本上,我正在尝试创建一个执行以下操作的 py 脚本:

  1. 在目录中搜索名称符合特定条件的文件。
  2. 收集文件名和路径,并将它们添加到字典中。
  3. 打印这样收集的文件: 1 保险2013.xls 2 保险2015.xlsx 3 保险2019.xls
  4. 允许用户选择他们想要打开的文件。

我不断收到此错误代码: NameError:名称“file_dict”未定义

我做错了什么? 任何帮助将不胜感激。谢谢。 :)

import os, glob
import pandas as pd

def find_files():

    # empty dictionary
    file_dict = {}

    # path
    downloads = str(Path.home() / "Downloads")

    # search whole pc for files with keywords to open
    for file, file_path in glob.iglob(downloads + "/**/*.{xls,xlsx}", 
                                      recursive=True):

        # collect filename and file path
        file_path = os.path.abs(file)
        filename = str(file_path.split("/")[-1])

        # add nested dictionary to dictionary
        dict_num = 1
        file_num = 1

        file_dict[dict_num] = {file_num: filename, path: file_path}
        dict_num += 1
        file_num += 1


def select_file(file_dict):

    # ensuring file is correct one
    for filename in file_dict.items():
        print(file_dict[filename])

    # user selects file 
    try:
            file_select = pyip.inputNum('Please input the number next to the file '
                                        'you would like to filter.', min=1, 
                                         max=len(file_dict.items()), blank=False)
    except:
            print('That is not a valid option, please select a file.')

def open_file(file_select, f_path):

    # match file number to filename and path
    for file_num, path in file_dict.items():
            if file_select == file_dict[file_num]:
                    f_path = str(path[key])
    # open file 
    pf.ExcelFile(f'{f_path})
pandas path nested filenames glob
© www.soinside.com 2019 - 2024. All rights reserved.