os.path.basename ()과 os.path.dirname ()의 차이점은 무엇입니까?


139

차이점은 무엇이며 os.path.basename()그리고 os.path.dirname()?

나는 이미 답을 찾고 링크를 읽었지만 이해하지 못했습니다. 누구나 간단한 설명을 할 수 있습니까?

답변:


273

두 함수 모두 함수를 사용하여 os.path.split(path)경로 이름 path을 쌍으로 나눕니다 . (head, tail).

os.path.dirname(path)함수는 경로의 헤드를 반환합니다.

예 : dirname은 '/foo/bar/item'입니다 '/foo/bar'.

os.path.basename(path)함수는 경로의 꼬리를 반환합니다.

예 : '/foo/bar/item'반품 의 기본 이름'item'

보낸 사람 : http://docs.python.org/2/library/os.path.html#os.path.basename


24
당신이 대체 할 경우 기억 item으로 item/다음 디렉토리 인 os.path.split('foo/bar/item/')반환 ('foo/bar/item', '').
jkdev

1
경로가 파일 인 경우 어떻게됩니까 (예 : "foo.bar")?
ZhaoGang

4
@jkdev 예, 경로에서 마지막 디렉토리 이름을 얻으려면 다음을 사용해야합니다.os.path.basename(os.path.dirname(path))
tli2020

@ZhaoGang 전체 경로가 파일 이름 인 경우 os.path.basename (file_name)은 파일 이름을 here,을 'foo.bar'반환하고 os.path.dirname (file_name)은 빈 문자열을 반환합니다 ''.
jkdev

4

위에서 Breno가 언급 한 내용을 요약하면

파일 경로가있는 변수가 있다고 가정 해보십시오.

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) 문자열을 반환 'myfile.py'

os.path.dirname(path)문자열을 반환합니다 '/home/User/Desktop'(후행 슬래시 '/'없이).

이 함수는 전체 경로 이름이 지정된 파일 이름 / 디렉토리 이름을 가져와야 할 때 사용됩니다.

파일 경로가 파일 이름 인 경우 (예 : path = '/home/User/Desktop/myfile.py'그냥있는 대신 myfile.py) os.path.dirname(path)빈 문자열을 반환합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.