0

I have a file abc.py under the workspace dir.

I am using os.listdir('/home/workspace/tests') in abc.py to list all the files (test1.py, test2.py...)

I want to generate the path '/home/workspace/tests' or even '/home/workspace' instead of hardcoding it.

I tried os.getcwd() and os.path.dirname(os.path.abspath(____file____)) but this instead generates the path where the test script is being run.

How to go about it?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Kat.S
  • 587
  • 2
  • 7
  • 13
  • 1
    Generate it from what information? How is `/home/workspace/tests` related to the working directory, the location of the script/module, or some other data you have available? – Wooble May 21 '14 at 12:32
  • The only paths available to the script are the current working directory and the location the file is placed. How is the Python script to 'know' about `/home/workspace` otherwise? What is that path based on? – Martijn Pieters May 21 '14 at 12:32
  • If you want to list all the files in a directory then visit this duplicate http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python – ρss May 21 '14 at 12:33
  • (Also, naming your script `abc.py` is a mildly bad idea; `abc` is a stdlib module, although granted one that you're unlikely to use very often.) – Wooble May 21 '14 at 12:33
  • If `/home/workspace` is a home directory of a user, and you want to base your paths on that, have a look at [`os.path.expanduser`](https://docs.python.org/2/library/os.path.html#os.path.expanduser). – Lukas Graf May 21 '14 at 12:38

2 Answers2

0

The only way you can refer to a specific folder from which you don't relate in any way and you don't want to hardcode it, is to pass it as a parameter to the script (search for: command line argument)

0

I think you are asking about how to get the relative path instead of absolute one.

Absolute path is the one like: "/home/workspace"

Relative looks like the following "./../workspace"

You should construct the relative path from the dir where your script is (/home/workspace/tests) to the dir that you want to acces (/home/workspace) that means, in this case, to go one step up in the directory tree.

You can get this by executing: os.path.dirname(os.path.join("..", os.path.abspath(__file__)))

The same result may be achieved if you go two steps up and one step down to workspace dir: os.path.dirname(os.path.join("..", "..", "workspace", os.path.abspath(__file__)))

In this manner you actually can access any directory without knowing it's absolute path, but only knowing where it resides relatively to your executed file.