Getting the current path from which the module is called
I have a python module that I have built and it is in /usr/local/lib/python3.4/site-packages/my_module1
. In a module, I have the following:
class Class1(object);
def __init__(self, file_name):
self.file_name = file_name # how can I get the full path of file_name?
How do I get the full one file_name
? That is, if it's just a filename without a path, add the current folder from which the module is called . Otherwise, treat the filename as a fully qualified path.
# /users/me/my_test.py
from module1 import Class1
c = Class1('my_file1.txt') # it should become /users/me/my_file1.txt
c1 = Class1('/some_other_path/my_file1.txt') # it should become /some_other_path/my_file1.txt/users/me/my_file1.txt
+3
source to share
1 answer
Update: Sorry. I misread your question. All you have to do is go through filename
, therefore os.path.abspath()
.
Example:
import os filename = os.path.abspath(filename)
To satisfy your second case (which I find rather strange):
import os
if os.path.isabs(filenaem):
filename os.path.join(
os.path.join(
filename,
os.getcwd()
),
os.path.basename(filename)
)
+2
source to share