I am creating various HTML file parts, image thumbnails etc. from within a CodeIgniter application tree using cron-scheduled Python 2.7 programs on Linux. The actual Python programs exist under the CodeIgniter tree in a subdirectory one level below the application directory as follows.
codeigniter/web-root
|
application
| |
| scripts
| | |
| | my-program.py
| |
| database
| |
| database.sqlite
images
I want to determine the codeigniter/web-root directory from within my-program.py using methods from the os.path module. However, the absolute path to the codeigniter/web-root is different on the development and production environments so I prefer not to hardwire this path information into the Python program itself.
The current script(s) use the following construct to determine the absolute path of "codeigniter/web-root" which is two directory levels above the script itself in both environments.
#!/bin/env python2.7
import os.path
ci_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Is there a cleaner way to determine the top level(ci_root) directory without using multiple os.path.dirname calls?
2 Answers 2
import os.path
print os.path.abspath(__file__+'/../../..') # the directory three levels up
I was pleasantly surprised that
- abspath() managed to parse correctly, without using os.path.join()
- We didn't have to strip out the filename before we build the path
For cross platform compatibility if abspath's parsing does not work, we could use something less readable, e.g.
- os.path.sep instead of '/'
- os.path.join()
Comments
Find the real path based on the relative path of "up three directories," and extract the last part of that real path.
[Edit: In response to your comment I have revised this. In my opinion it is getting complex
enough that your chain of dirname's is better. At least it is easy to understand what it happening.]
from os import path as p
_, ci_root = p.split(p.abspath(p.join(__file__, '../../..')))
2 Comments
Explore related questions
See similar questions with these tags.