Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

python - Get location of the .py source file

Say I have a python file in directory e like this:

/a/b/c/d/e/file.py

Under directory e I have a few folders I want to access but if file.py is executed from anywhere else rather than from folder e the relative path won't work for me. Also folder e could be located anywhere but always with the a set of sub folders so absolute path will not work.

First, is there any function to get the absolute path in relation to the source files location?

If not, any ideas how to sort this out? Grab the command line used and add the CWD together?

My problem here is that this folder are being installed on 20 different machines and OS's and I want it to be as dynamic as possible with little configurations and "rules" where it has to be installed etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
# in /a/b/c/d/e/file.py
import os
os.path.dirname(os.path.abspath(__file__)) # /a/b/c/d/e

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...