4 回答

TA貢獻1777條經(jīng)驗 獲得超3個贊
您需要提供絕對路徑
import os
CURRENT_DIR = os.path.dirname(__file__) # Gets directory path of the current python module
cost_path = os.path.join(CURRENT_DIR , 'CostEstimation_001.xlsx')

TA貢獻1825條經(jīng)驗 獲得超4個贊
例如,要在根目錄中查找名為 Mattermost 的目錄,您可以使用以下命令。
sudo?find?/?-name?"mattermost"?-type?d
用于查找文件位置
sudo?find?/?-name?"mattermost"?-type?f
如果您想獲取腳本中的文件位置,請按照grismar的建議使用 os 模塊

TA貢獻1906條經(jīng)驗 獲得超10個贊
您可能正在尋找__file__.
創(chuàng)建一個名為的腳本try_this.py并運行它:
from pathlib import Path
print(__file__)
print(Path(__file__).parent)
print(Path(__file__).parent / 'some_other_file.csv')
結(jié)果應(yīng)該是這樣的:
C:/Location/try_this.py
C:\Location
C:\Location\some_other_file.csv

TA貢獻1836條經(jīng)驗 獲得超3個贊
如果導(dǎo)入 os 模塊,有一些函數(shù)可以幫助您: os.path.abspath(如果某個東西已經(jīng)在同一目錄中,它會為您提供路徑)和 os.walk(它會搜索它并提供它的位置) 。
import os
exe = 'something.exe'
#if the exe just in current dir
print os.path.abspath(exe)
# output
# D:\python\note\something.exe
#if we need find it first
for root, dirs, files in os.walk(r'D:\python'):
for name in files:
if name == exe:
print os.path.abspath(os.path.join(root, name))
# output
# D:\python\note\something.exe
添加回答
舉報