4 回答
TA貢獻1777條經驗 獲得超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條經驗 獲得超4個贊
例如,要在根目錄中查找名為 Mattermost 的目錄,您可以使用以下命令。
sudo?find?/?-name?"mattermost"?-type?d
用于查找文件位置
sudo?find?/?-name?"mattermost"?-type?f
如果您想獲取腳本中的文件位置,請按照grismar的建議使用 os 模塊
TA貢獻1906條經驗 獲得超10個贊
您可能正在尋找__file__.
創建一個名為的腳本try_this.py并運行它:
from pathlib import Path
print(__file__)
print(Path(__file__).parent)
print(Path(__file__).parent / 'some_other_file.csv')
結果應該是這樣的:
C:/Location/try_this.py
C:\Location
C:\Location\some_other_file.csv
TA貢獻1836條經驗 獲得超3個贊
如果導入 os 模塊,有一些函數可以幫助您: os.path.abspath(如果某個東西已經在同一目錄中,它會為您提供路徑)和 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
添加回答
舉報
