在与python文件相同的文件夹中定义文件位置

2024-06-16 13:54:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想定义以下文件的文件路径,这些文件与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)

该位置用于另一个函数


Tags: 文件pathobjinputbypngtemplatexlsx
3条回答

您可能正在寻找__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

如果导入操作系统模块,有几个功能可以帮助您: abspath,如果某个对象已经在同一目录中,则获取该对象的路径,以及 它会搜索它并给出它的位置

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

您需要提供绝对路径

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

相关问题 更多 >