user266003
user266003

Reputation:

Getting the current path from where a module is being called

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

Upvotes: 3

Views: 84

Answers (1)

James Mills
James Mills

Reputation: 19050

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)
    )

Upvotes: 1

Related Questions