简体   繁体   English

如何获取文件路径目录并使用它来读取我的Excel文件? (苹果电脑)

[英]How to get filepath directory and use it to read my excel file? (Mac)

I'm creating a basketball data visualization app, and I've already completed the GUI, now just trying to import my database which is an excel file. 我正在创建一个篮球数据可视化应用程序,并且我已经完成了GUI,现在只是尝试导入我的数据库(一个excel文件)。 I'm using pandas, and when I run this code, I get the "No such file or directory" error. 我正在使用熊猫,当我运行此代码时,出现“没有这样的文件或目录”错误。 I understand I must get the filepath, but how do I do this (Mac OS X) and implement it to direct my code to my file? 我知道我必须获取文件路径,但是如何做到这一点(Mac OS X)并实现它以将代码定向到文件中?

I tried directly copying and pasting the filepath with path = r'C:(insert path here)' 我尝试使用path = r'C :(在此处插入路径)'直接复制和粘贴文件路径

#Basketball DataVis (Data Visualization)
#pylint:disable = W0614
#By Robert Smith

#Import 
import tkinter
import os
import pandas as pd
from tkinter import *
from PIL import Image, ImageTk 
from pandas import *

#Import the excel file to use as a database
data = pd.read_excel("nbadata.xlsx", sheetname= "Sheet1")

Easiest way is to open an instance of the terminal and then drag the file into the terminal screen - this will print the path which you can then use in your script. 最简单的方法是打开终端的一个实例,然后将文件拖到终端屏幕中-这将打印您可以在脚本中使用的路径。

Note that mac filepaths don't begin with C: 请注意,mac文件路径不是以C开头:

I will suggest you to use recursive approach to solve your problem if you don't know where is your xlsx file (so you can't provide relative or absolute path) but you know the exact name of it and you also know the root directory under which this file exists. 如果您不知道xlsx文件在哪里(因此您不能提供相对或绝对路径),但是您知道它的确切名称并且也知道根目录,我建议您使用递归方法来解决问题。该文件所在的目录。

For this kind of scenario, just pass the root path and filename to the recursive function and it will give a list of absolute paths of all matched file names. 对于这种情况,只需将根路径和文件名传递给递归函数,它将提供所有匹配文件名的绝对路径列表。

Finally you can choose the 1st one from that list if you are sure there're no more files with the same name or you can print the list on console and retry. 最后,如果您确定没有其他同名文件,或者可以在控制台上打印该列表并重试,则可以从该列表中选择第一个。

I found this method best in my case and I have presented a simple example for that as follows. 我发现这种方法最适合我,下面给出了一个简单的示例。

Directory structure: 目录结构:

H:\RishikeshAgrawani\Projects\GenWork\Python3\try\test>tree . /f
Folder PATH listing for volume New Volume
Volume serial number is C867-828E
H:\RISHIKESHAGRAWANI\PROJECTS\GENWORK\PYTHON3\TRY\TEST
│   tree
│
├───c
│       docs.txt
│
├───cpp
│       docs.md
│
├───data
│       nbadata.xlsx
│
├───js
│       docs.js
│
├───matlab
│       docs.txt
│
├───py
│   │   docs.py
│   │
│   └───docs
│           docs.txt
│
└───r
        docs.md

Here is the recursive implementation, please have a look and try. 这是递归的实现,请尝试一下。

import os 

def search_file_and_get_abspaths(path, filename):
    """
    Description
    ===========
        - Gives list of absolute path of matched file names by performing recursive search
        - [] will be returned in there is no such file under the given path
    """
    matched_paths = []

    if os.path.isdir(path):
        files = os.listdir(path)

        for file in files:
            fullpath = os.path.join(path, file)

            if os.path.isdir(fullpath):
                # Recusive search in child directories
                matched_paths += search_file_and_get_abspaths(fullpath, filename)
            elif os.path.isfile(fullpath):
                if fullpath.endswith(filename):
                    if not path in matched_paths:
                        matched_paths.append(fullpath)

    return matched_paths


if __name__ == "__main__":
    # Test case 1 (Multiple files exmample)
    matched_paths = search_file_and_get_abspaths(r'H:\RishikeshAgrawani\Projects\GenWork\Python3\try\test', 'docs.txt');
    print(matched_paths)

    # Test case 2 (Single file example)
    matched_paths2 = search_file_and_get_abspaths(r'H:\RishikeshAgrawani\Projects\GenWork\Python3\try\test', 'nbadata.xlsx');
    print(matched_paths2)
    # ['H:\\RishikeshAgrawani\\Projects\\GenWork\\Python3\\try\\test\\c\\docs.txt', 'H:\\RishikeshAgrawani\\Projects\\GenWork\\Python3\\try\\test\\matlab\\docs.txt', 'H:\\RishikeshAgrawani\\Projects\\GenWork\\Python3\\try\\test\\py\\docs\\docs.txt']

    if matched_paths2:
        xlsx_path = matched_paths2[0] # If your file name is unique then it will only be 1
        print(xlsx_path) # H:\RishikeshAgrawani\Projects\GenWork\Python3\try\test\data\nbadata.xlsx

        data = pd.read_excel(xlsx_path, sheetname= "Sheet1") 
    else:
        print("Path does not exist")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将文件写入 memory 文件路径并从 Python 中的 memory 文件路径读取? - How to write file to memory filepath and read from memory filepath in Python? 如何获取上传文件的文件路径? - How do I get the filepath of an uploaded file? 如何获取烧瓶中文件的文件路径? - How can you get the filepath of a file in flask? 如何在python中转义正斜杠,以便open()将我的文件视为要写入的文件名,而不是要读取的文件路径? - How do I escape forward slashes in python, so that open() sees my file as a filename to write, instead of a filepath to read? 如何从 /Filestore/tables/ 目录中的 databricks 中使用 pandad pd.read_excel 读取 excel 文件? - how to read an excel file using pandad pd.read_excel in databricks from /Filestore/tables/ directory? 如何将熊猫read_excel()用于多张Excel文件? - How to use pandas read_excel() for excel file with multi sheets? Pandas.read_excel 从文件路径 - Pandas.read_excel from filepath 如何从 Mac OS 目录中的所有文件中获取 MAC 时间/文件属性 - How can you get MAC times/file attributes from all files in directory on Mac OS 使用 pandas python 读取目录中的 excel 文件 - read the excel file in directory using pandas python 如何使我的scrapy读取同一目录中的文件? - How to make my scrapy read the file which in the same directory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM