亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

定義文件位置與python文件在同一文件夾中

定義文件位置與python文件在同一文件夾中

楊__羊羊 2023-10-18 15:48:11
我想定義以下文件的文件路徑,這些文件與 python 文件位于同一位置。谷歌搜索中的所有問題都涉及打開文件但不獲取位置。如何才能做到這一點?abaqus_input_template_path = '/30_30_0-8.inp'cost_path = '/CostEstimation_001.xlsx'pole_option_path = '/??.xlsx'chord_option_path = '/?,??? .xlsx'diagonal_option_path = '/??.xlsx'element_label_by_type_path = '/Element label number by Type.xlsx'tunnel_png_path = '/tunnel.png'mip_obj_path = '/mip_res.obj'編輯:test =project(abaqus_input_template_path,cost_path,pole_option_path,chord_option_path,             diagonal_option_path,element_label_by_type_path,tunnel_png_path,mip_obj_path)該位置在另一個函數中使用。
查看完整描述

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


查看完整回答
反對 回復 2023-10-18
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

例如,要在根目錄中查找名為 Mattermost 的目錄,您可以使用以下命令。

sudo?find?/?-name?"mattermost"?-type?d

用于查找文件位置

sudo?find?/?-name?"mattermost"?-type?f

如果您想獲取腳本中的文件位置,請按照grismar的建議使用 os 模塊


查看完整回答
反對 回復 2023-10-18
?
隔江千里

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


查看完整回答
反對 回復 2023-10-18
?
米脂

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


查看完整回答
反對 回復 2023-10-18
  • 4 回答
  • 0 關注
  • 273 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號