Getting the current path from where a module is being called

时间:2015-04-23 05:13:44

标签: python python-3.x

I have a python module I built myself and it's located in /usr/local/lib/python3.4/site-packages/my_module1. In the module I have this:

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 of file_name? That is, if it's just a file name without a path, then append the current folder from where the module is being called. Otherwise, treat the file name as a full 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

1 个答案:

答案 0 :(得分:1)

Update: Sorry about that. I mis-read your question. All you need to do is pass filename so os.path.abspath().

Example:

import os

filename = os.path.abspath(filename)

To cater for your 2nd case (which I find quite weird):

import os

if os.path.isabs(filenaem):
    filename os.path.join(
        os.path.join(
            filename,
            os.getcwd()
        ),
        os.path.basename(filename)
    )