2012-03-09 68 views
0

我正在试图查找看起来像是谁的路径的文件。从具有未知中间目录的目录中获取文件,使用python

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

我知道{{数}}的,但我不知道是什么{{未知}}是的,但我不知道,只是有其中之一。

比方说,号码是1231,当我使用的shell命令ls这样

ls /foo/1231/*/bar 

我得到我想要的结果,例如,它打印出

/foo/1231/some_name/bar 

现在,我想要使用python获取这个文件名,但是我所有的尝试都失败了。我首先尝试的是,

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

但它抱怨说没有目录/foo/1231/*/bar。 我也尝试使用Python模块从github.com/amoffat/pbs,但也说,将引发类似的错误。

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 

然后我用subprocess.check_output试过,但出现同样的错误。

然后我尝试使用os.system(“ls/foo/123/*/bar”),这会打印出一个有意义的结果,我无法捕获它,因为在os.system的文档中提到Changes to sys.stdin, etc. are not reflected in the environment of the executed command.

有没有人知道一种方法来获得我的愿望?谢谢

回答

2

两种方式暗示自己。

如果真的有只有一个中间的目录,你可以像这样解压:

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

或者你可以使用glob标准模块:

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