简体   繁体   中英

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. 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?

I tried directly copying and pasting the filepath with path = r'C:(insert path here)'

#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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM