2012-03-09 2 views
0

누구의 경로가 보이는 파일을 찾으려고합니다.파이썬으로 알려지지 않은 가운데 디렉토리가있는 디렉토리에서 파일을 가져 오는 중

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

내가 알고있는 {{수}}하지만 내가 {{알 수없는}} 뭔지 모르겠지만, 난 단지 그들 중 하나가 있다는 것을 알고있다.

예를 들어, 그것은, 내가 원하는 이제

/foo/1231/some_name/bar 

를 출력 내가이

ls /foo/1231/*/bar 

같은 쉘 명령 ls을 사용하면 내가 원하는 결과를 얻을 수는 1231입니다 말할 수 있습니다 파이썬을 사용하여이 파일 이름을 얻으려면,하지만 내 모든 시도는 실패했습니다. 처음 시도한 것은

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

/foo/1231/*/bar입니다. 나는 또한 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 

I는 다음 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] 
관련 문제