devinxxd
devinxxd

Reputation: 5

Define the file location in the same folder as the python file

I want to define the file paths of the following files which are in the same location as the python file. All the questions from the google searches deal with opening the file but not getting the location. How can this be done?

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'

Edit:

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)

The location is used in another function.

Upvotes: 0

Views: 1479

Answers (4)

Msv
Msv

Reputation: 1371

For example to find a directory named mattermost in root directory you can use following.

sudo find / -name "mattermost" -type d

for finding file location

sudo find / -name "mattermost" -type f

If you want to get the file locations in your script use os module as suggested by grismar

Upvotes: 0

Grismar
Grismar

Reputation: 31339

You're probably looking for __file__.

Create a script called try_this.py and run it:

from pathlib import Path

print(__file__)
print(Path(__file__).parent)
print(Path(__file__).parent / 'some_other_file.csv')

The result should be something like:

C:/Location/try_this.py
C:\Location
C:\Location\some_other_file.csv

Upvotes: 0

Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

You need to provide absolute paths

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

Upvotes: 1

Maxijazz
Maxijazz

Reputation: 185

If you import the os module, there are a few functions that can help you: os.path.abspath, which gets you something's path if it's already in the same directory, and os.walk, which searches for it and gives you it's location.

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

Upvotes: 0

Related Questions