python实战根据excel的文件名称这一列的内容,找到电脑D盘的下所对应的文件位置,要求用程序实现

今天客户需要 根据excel的文件名称这一列的内容,找到电脑D盘的下所对应的文件位置,要求用程序实现

数据样例:记录.xlsx

解决代码:

1、安装必要的库:

python 复制代码
pip install pandas openpyxl

2、编写Python脚本:

python 复制代码
import os
import pandas as pd

def find_files_in_directory(file_names, search_path):
    file_locations = {}
    for root, dirs, files in os.walk(search_path):
        for name in files:
            if name in file_names:
                file_locations[name] = os.path.join(root, name)
    return file_locations

def main():
    # 读取Excel文件
    excel_path = '记录.xlsx'  # 替换为你的Excel文件路径
    df = pd.read_excel(excel_path)

    # 假设文件名在名为 'filename' 的列中
    file_names = df['文件名称'].tolist()

    # 定义要搜索的目录
    search_path = 'D:\\'

    # 查找文件
    file_locations = find_files_in_directory(file_names, search_path)

    # 输出结果
    for file_name, file_path in file_locations.items():
        print(f'文件名: {file_name} 位于: {file_path}')

if __name__ == '__main__':
    main()
python 复制代码
代码说明:
导入必要的库:os 用于遍历文件系统,pandas 用于读取Excel文件。
定义函数 find_files_in_directory:遍历指定目录及其子目录,查找与给定文件名匹配的文件,并记录其完整路径。
在 main 函数中:
读取Excel文件,获取文件名列表。
指定搜索目录(D盘)。
调用 find_files_in_directory 函数查找文件并输出结果。
你需要将 path_to_your_excel_file.xlsx 替换为实际的Excel文件路径,并确保Excel文件中有一列包含文件名,这里假设列名为 filename。运行脚本后,程序会在D盘中查找这些文件,并输出它们的路径。
相关推荐
从零开始学习人工智能3 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
WWJA王文举4 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
卷无止境4 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13145 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教5 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教5 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境6 小时前
FastAPI 的Admin面板生态
后端·python
qq_448011166 小时前
C语言中的动态内存分配
c语言·开发语言·php
ctlover6 小时前
Streamlit 框架
python
ι:6 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机