簡體   English   中英

如何獲取文件路徑目錄並使用它來讀取我的Excel文件? (蘋果電腦)

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

我正在創建一個籃球數據可視化應用程序,並且我已經完成了GUI,現在只是嘗試導入我的數據庫(一個excel文件)。 我正在使用熊貓,當我運行此代碼時,出現“沒有這樣的文件或目錄”錯誤。 我知道我必須獲取文件路徑,但是如何做到這一點(Mac OS X)並實現它以將代碼定向到文件中?

我嘗試使用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")

最簡單的方法是打開終端的一個實例,然后將文件拖到終端屏幕中-這將打印您可以在腳本中使用的路徑。

請注意,mac文件路徑不是以C開頭:

如果您不知道xlsx文件在哪里(因此您不能提供相對或絕對路徑),但是您知道它的確切名稱並且也知道根目錄,我建議您使用遞歸方法來解決問題。該文件所在的目錄。

對於這種情況,只需將根路徑和文件名傳遞給遞歸函數,它將提供所有匹配文件名的絕對路徑列表。

最后,如果您確定沒有其他同名文件,或者可以在控制台上打印該列表並重試,則可以從該列表中選擇第一個。

我發現這種方法最適合我,下面給出了一個簡單的示例。

目錄結構:

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

這是遞歸的實現,請嘗試一下。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM