"/", "\"를 사용한 플랫폼 독립적 경로 연결?
파이썬에는 변수 base_dir
와 filename
. 나는 그것들을 연결하여 fullpath
. 그러나 창문 아래 \
에서 POSIX를 사용해야합니다 /
.
fullpath = "%s/%s" % ( base_dir, filename ) # for Linux
플랫폼을 독립적으로 만드는 방법은 무엇입니까?
이를 위해 os.path.join () 을 사용하고 싶습니다 .
문자열 연결 등이 아닌 이것을 사용하는 장점은 경로 구분 기호와 같은 다양한 OS 특정 문제를 알고 있다는 것입니다. 예 :
import os
에서 윈도우 7 :
base_dir = r'c:\bla\bing'
filename = r'data.txt'
os.path.join(base_dir, filename)
'c:\\bla\\bing\\data.txt'
아래에서 리눅스 :
base_dir = '/bla/bing'
filename = 'data.txt'
os.path.join(base_dir, filename)
'/bla/bing/data.txt'
운영체제 모듈 등을 통한 경로에 사용되는 세퍼레이터 등의 디렉토리 경로 조작 및 OS의 특정 정보를 알아 내기위한 여러 가지 유용한 방법을 포함 os.sep을
사용 os.path.join()
:
import os
fullpath = os.path.join(base_dir, filename)
을 os.path의 모듈은 플랫폼 독립적 인 경로 조작에 필요한해야하는 방법이 모두 포함되어 있지만, 경우에 당신은 경로 분리가 사용할 수있는 현재의 플랫폼이 무엇인지 알아야합니다 os.sep
.
여기에서 오래된 질문을 파헤 치지 만 Python 3.4 이상 에서는 pathlib 연산자를 사용할 수 있습니다 .
from pathlib import Path
# evaluates to ./src/cool-code/coolest-code.py on Mac
concatenated_path = Path("./src") / "cool-code\\coolest-code.py"
os.path.join()
운이 좋게도 최신 버전의 Python을 실행하는 것보다 잠재적으로 더 읽기 쉽습니다. 그러나 경직된 환경이나 레거시 환경에서 코드를 실행해야하는 경우 이전 버전의 Python과의 호환성도 절충합니다.
import os
path = os.path.join("foo", "bar")
path = os.path.join("foo", "bar", "alice", "bob") # More than 2 params allowed.
이에 대한 도우미 클래스를 만들었습니다.
import os
class u(str):
"""
Class to deal with urls concat.
"""
def __init__(self, url):
self.url = str(url)
def __add__(self, other):
if isinstance(other, u):
return u(os.path.join(self.url, other.url))
else:
return u(os.path.join(self.url, other))
def __unicode__(self):
return self.url
def __repr__(self):
return self.url
사용법은 다음과 같습니다.
a = u("http://some/path")
b = a + "and/some/another/path" # http://some/path/and/some/another/path
참고 URL : https://stackoverflow.com/questions/10918682/platform-independent-path-concatenation-using
'Development Tip' 카테고리의 다른 글
os.listdir ()을 사용하여 숨겨진 파일을 무시하는 방법은 무엇입니까? (0) | 2020.10.31 |
---|---|
Rails 3는 유효성 검사 및 콜백 건너 뛰기 (0) | 2020.10.31 |
oh-my-zsh는 느리지 만 특정 Git 저장소에서만 (0) | 2020.10.31 |
Bash의 배열에서 고유 한 값을 얻으려면 어떻게해야합니까? (0) | 2020.10.31 |
Git Bash 터미널에서 Bitbucket에 새 저장소를 만드시겠습니까? (0) | 2020.10.31 |