简体   繁体   中英

How to get a py file's path?

I want to use other folder's data in my python code. The file structure like this:

-- Data
   -- data.txt
-- Src
   -- app.py

So I write the code as blow:

fileName = os.path.abspath('../Data/data.txt')

The code is right, only run in the Src folder. But when I run the py code, in my home folder, or other folder. It was wrong. I know why, because it is path problem. So, Here is my question, how to make it right? Could anybody help me?

I am guessing there is a better way, but this is pretty straight forward

import os

# get the directory of the executed python file
src_path = os.path.dirname(os.path.abspath(__file__))

# get the directory of data relative to the src_path
data_path = os.path.join(src_path, "../data/data.txt")

# profit ?
print open(data_path).read()

Examples

/tmp/src > python app.py
Hello World!

/tmp > python src/app.py
Hello World!

You need to specify the path to the data file, you can hardcode it or pass it as an arg with a default value (the better solution)

import sys

if __name__ == '__main__':
    fileName = sys.argv[1] if len(sys.argv==2) else '/the/default/path'

''' your code''''   

when passing args to a Python script the first arg is the name of the script itself

Also if you needed to get the current directory path within your script:

import os
current_path = os.getcwd()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM