2017-04-11 2 views
2

디렉토리에 대한 경로와 그 디렉토리에 들어있는 파일의 경로 (가능한 많은 디렉토리를 중첩 할 수 있음)를받는 스크립트를 작성하고 외부 디렉토리를 기준으로이 파일에 대한 경로를 리턴합니다.파이썬에서 파일 이름의 접두사를 제거하려면 어떻게해야합니까?

예를 들어 외부 디렉토리가 /home/hugomg/foo이고 내부 파일이 /home/hugomg/foo/bar/baz/unicorns.txt이면 bar/baz/unicorns.txt을 출력하고 싶습니다.

import os 

dir_path = "/home/hugomg/foo" 
file_path = "/home/hugomg/foo/bar/baz/unicorns.py" 

dir_path = os.path.realpath(dir_path) 
file_path = os.path.realpath(file_path) 

if not file_path.startswith(dir_path): 
    print("file is not inside the directory") 
    exit(1) 

output = file_path[len(dir_path):] 
output = output.lstrip("/") 
print(output) 

을하지만,이 작업을 수행 할 수있는보다 강력한 방법이 있습니다 :

지금은 realpath과 문자열 조작을 사용하여 뭐하는 거지? 현재 솔루션이 올바른 방법이라고 확신하지 못합니다. realpath와 함께 startswith를 사용하여 한 파일이 다른 파일 안에 있는지 테스트하는 올바른 방법입니까? 그리고 제거해야 할지도 모르는 선도적 인 슬래시로 어색한 상황을 피할 수있는 방법이 있습니까?

답변

1

os.path 모듈의 commonprefixrelpath을 사용하여 두 경로 중 가장 긴 공통 접두사를 찾을 수 있습니다. 항상 realpath을 사용하는 것이 좋습니다.

import os 
dir_path = os.path.realpath("/home/hugomg/foo") 
file_path = os.path.realpath("/home/hugomg/foo/bar/baz/unicorns.py") 
common_prefix = os.path.commonprefix([dir_path,file_path]) 

if common_prefix != dir_path: 
    print("file is not inside the directory") 
    exit(1) 
print(os.path.relpath(file_path, dir_path)) 

출력 :

bar/baz/unicorns.txt 
+0

이도하지 제거하는 접두사로, 제거 할 문자의 집합으로의 매개 변수를 취급 lstrip ... 오프 느낀다. 그리고'dir_path'와'file_path'가 정규화되지 않았다면 여전히 작동합니까, 절대 경로명? – hugomg

+0

아마도'relpath'가 더 적합할까요? – abccd

+0

[이 질문] (http://stackoverflow.com/questions/7287996/python-get-relative-path-from-comparing-two-absolute-paths/7288019#7288019)는 내가 묻는 것과 비슷합니다. BTW, 누군가 commonprefix가 commonpath 함수에 찬성하여 더 이상 사용되지 않는다고 지적했습니다. – hugomg

관련 문제