developer tip

Python, 디렉토리 문자열에 후행 슬래시 추가, OS 독립적

optionbox 2020. 8. 19. 07:58
반응형

Python, 디렉토리 문자열에 후행 슬래시 추가, OS 독립적


후행 슬래시가없는 경우 디렉토리 문자열에 후행 슬래시 ( /* nix, \win32의 경우)를 추가하려면 어떻게해야합니까? 감사!


os.path.join(path, '') 아직없는 경우 후행 슬래시를 추가합니다.

당신은 할 수있다 os.path.join(path, '', '')또는 os.path.join(path_with_a_trailing_slash, '')당신은 여전히 하나의 후행 슬래시를 얻을 것이다.


디렉토리와 파일 이름을 연결하려면

os.path.join(directory, filename)

.\..\..\blah\경로를 제거 하려면

os.path.join(os.path.normpath(directory), filename)

다음과 같이 수동으로 수행 할 수 있습니다.

path = ...

import os
if not path.endswith(os.path.sep):
    path += os.path.sep

그러나 일반적으로 사용하는 것이 훨씬 더 깨끗합니다 os.path.join.


다음과 같이 사용할 수 있습니다.

os.path.normcase(path)
    Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes.

그렇지 않으면 페이지에서 다른 것을 찾을 수 있습니다 .

참고 URL : https://stackoverflow.com/questions/2736144/python-add-trailing-slash-to-directory-string-os-independently

반응형