os.path.join에 대한 Pathlib 대안이 있습니까?
현재 다음을 사용하여 파일의 상위 디렉토리에 액세스하는 중입니다.Pathlib
다음과 같이:
Path(__file__).parent
인쇄하면 다음과 같은 출력이 나타납니다.
print('Parent: ', Path(__file__).parent)
#output
/home/user/EC/main-folder
그main-folder
을 가지고 있습니다..env
액세스하고 싶고 이를 위해 상위 경로에 가입하고 싶은 파일.env
지금, 저는 했습니다.
dotenv_path = os.path.join(Path(__file__).parent, ".env")
효과가 있는 것.하지만 저는 알고 싶습니다, 만약에.Pathlib
와 교대로.os.path.join()
다음과 같은 것:
dotenv_path = pathlib_alternate_for_join(Path(__file__).parent, ".env")
예, 다음이 있습니다.
env_path = Path(__file__).parent / ".env"
/
당신이 필요한 것은 전부입니다.이것은 다른 OS에서 작동합니다.
다음과 같은 것을 사용할 수 있습니다.
(Path(__file__).parent).joinpath('.env')
설명서:
의 다음 정의는 다음과 같습니다.filepath
OS.path.path.path에 더 가까운 정신?
import pathlib
main_dir = 'my_main_dir'
sub_dir = 'sub_dir'
fname = 'filename.tsv'
filepath = pathlib.PurePath(main_dir, sub_dir, fname)
경로 개체 및 문자열을 간단하게 결합할 수 있습니다.
import pathlib
script_parent_path = pathlib.Path(__file__).parent
my_dir = ".env"
my_new_path = pathlib.Path(script_parent_path, my_dir)
print(my_new_path)
그 이유는 다음과 같습니다.
Pathlib의 생성자는 경로 세그먼트를 허용합니다.경로 세그먼트의 각 요소는 OS를 구현하는 개체인 경로 세그먼트를 나타내는 문자열일 수 있습니다.문자열 또는 다른 경로 개체를 반환하는 PathLike 인터페이스 - https://docs.python.org/3/library/pathlib.html#pathlib.PurePath
경로를 연결하는 가장 쉬운 방법은
Path(Path(__file__).parent,".env")
의 정의도 참조하십시오.
설명서에서 PurePath에 대해 다음 문장과 예제가 제공됩니다.
여러 개의 절대 경로가 주어지면 마지막 경로가 앵커로 사용됩니다(os.path.join()의 동작을 모방함).
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
어떻게 하는지 궁금해하는 사람들을 위해./
에서 내부적으로 작동합니다.pathlib.Path
:
# this is where the magic begins! (overload the '/' operator)
def __truediv__(self, key):
try:
return self._make_child((key,))
except TypeError:
return NotImplemented
def _make_child(self, args):
drv, root, parts = self._parse_args(args)
drv, root, parts = self._flavour.join_parsed_parts(
self._drv, self._root, self._parts, drv, root, parts)
return self._from_parsed_parts(drv, root, parts)
@classmethod
def _from_parsed_parts(cls, drv, root, parts):
self = object.__new__(cls)
self._drv = drv
self._root = root
self._parts = parts
return self # finally return 'self', which is a Path object.
언급URL : https://stackoverflow.com/questions/61321503/is-there-a-pathlib-alternate-for-os-path-join
'programing' 카테고리의 다른 글
모서리가 둥글고 그림자가 드리워진 UIView? (0) | 2023.05.14 |
---|---|
Postgre에서 특정 행 내보내기SQL 테이블을 INSERT SQL 스크립트로 사용 (0) | 2023.05.14 |
wpf에서 사용자 지정 윈도우 크롬을 만드는 방법은 무엇입니까? (0) | 2023.05.14 |
원격 컴퓨터의 디스크 용량 및 여유 공간을 얻는 방법 (0) | 2023.05.09 |
.Net이 잘못된 참조 어셈블리 버전을 선택합니다. (0) | 2023.05.09 |