Doboy
Doboy

Reputation: 11082

obtaining a file from a directory with a unknown middle directory, with python

I am trying to look a file that looks who's path looks like this.

/foo/{{number}}/{{unknown}}/bar

I know what {{number}} is but i do not know what {{unknown}} is, but I do know that there is only one of them.

Lets say number is 1231, when i use the shell command ls like this

ls /foo/1231/*/bar

I get the result I want, for example, it prints out

/foo/1231/some_name/bar

Now, I want to do get this filename using python, but all my attempts have failed. What I tried first was,

os.listdir( "/foo/1231/*/bar" )

but it complains that there is no directory /foo/1231/*/bar. I also tried using a python module from github.com/amoffat/pbs, but that too say that throws a similar error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/pbs.py", line 449, in __call__
    return RunningCommand(command_ran, process, call_args, actual_stdin)
  File "/usr/local/lib/python2.7/site-packages/pbs.py", line 140, in __init__
    if rc != 0: raise get_rc_exc(rc)(self.command_ran, self._stdout, self._stderr)
 pbs.ErrorReturnCode_1:

Ran: '/bin/ls /foo/123/*/bar'

STDOUT:



STDERR:

  /bin/ls: /foo/123/*/bar: No such file or directory

I then tried using subprocess.check_output, but same error occurred.

Then I tried using os.system( "ls /foo/123/*/bar" ), this prints out a meaningful result, there is no way for me to capture it, since on the documentation of os.system it says Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

Does anyone know a way to obtain what I desire? Thanks

Upvotes: 0

Views: 373

Answers (1)

ben w
ben w

Reputation: 2535

Two ways suggest themselves.

If there really is only one middle directory, you can extract it like so:

beginning = '/foo/1231'
mid = os.path.listdir(beginning)[0]
fullpath = os.path.join(beginning, mid, 'bar')

Or you can use the glob standard module:

fullpath = glob.glob('/foo/1231/*/bar')[0]

Upvotes: 2

Related Questions