pXAɊ܂܂gqƂȊO̕ɕƂ͂悭BsɂsplitextPath.stem^Path.suffix^Path.parent^Path.suffixesgB
̋L͉łBo^ijƑSĂ܂B
# pXgqƂȊO̕ɕ
from os.path import splitext
path = '/dir0/dir1/somefile.txt'
root, ext = splitext(path)
print(f'root: {root}, ext: {ext}') # root: /dir0/dir1/somefile, ext: .txt
# PathIuWFNgłparentstemgݍ킹
from pathlib import Path
path = Path(path)
print(f'path.stem: {path.stem}') # path.stem: somefile
print(f'path.suffix: {path.suffix}') # path.suffix: .txt
print(f'path.parent: {path.parent}') # path.parent: /dir0/dir1
root = Path(f'{path.parent}/{path.stem}')
print(f'root: {root}, ext: {path.suffix}') # root: /dir0/dir1/somefile, ext: .txt
# gqAĂꍇɂgqƂĕɂ
path = '/dir0/dir1/somefile.tar.gz'
root, ext = splitext(path)
print(f'root: {root}, ext: {ext}') # root: /dir0/dir1/somefile.tar, ext: .gz
def mysplitext(path):
root, ext = splitext(path)
exts = ext
while ext != '':
root, ext = splitext(root)
exts = ext + exts
return root, exts
root, ext = mysplitext(path)
print(f'root: {root}, ext: {ext}') # root: /dir0/dir1/somefile, ext: .tar.gz
path = Path(path) # root: /dir0/dir1/somefile, ext: .tar.gz
root = Path(f'{path.parent}/{path.stem}')
ext = path.suffix
print(f'root: {root}, ext: {ext}') # root: /dir0/dir1/somefile.tar, ext: .gz
print(path.suffixes) # ['.tar', '.gz']
def mysplitext(path):
parent = str(path.parent)
parent = '' if parent == '.' else parent
tmp = path.stem
while True:
stem = Path(tmp).stem
if stem == tmp:
break
tmp = stem
suffixes = ''.join(path.suffixes)
root = f'{parent}/{stem}' if parent else stem
return root, suffixes
root, ext = mysplitext(path)
print(f'root: {root}, ext: {ext}') # root: /dir0/dir1/somefile, ext: .tar.gz
@os.pathW[ɂ͓nꂽpXAgqƂȊO̕ɕsplitextiɂ͕APathIuWFNgȂǂwłjBsplitext̓pX^Ƃu(gqȊO, gq)vƂ^vɊ܂߂ĕԑB
@ȉɗB
from os.path import splitext
path = '/dir0/dir1/somefile.txt'
root, ext = splitext(path)
print(f'root: {root}, ext: {ext}') # root: /dir0/dir1/somefile, ext: .txt
@̗ł̓pXƂāu'/dir0/dir1/somefile.txt'vsplitextɓnĂB̂߁AgqƂȊOɕꂽu('/dir0/dir1/somefile', '.txt')vƂ^vԑĂ邱ƂB
@ApathlibW[PathNXɂstemsuffixBstem̓pX\ŏIvf̊gqO̕\Asuffix͊gq\B̂߁APɂ2邾łsplitextƂ͈قȂ錋ʂɂȂ邱ƂB
@ȉɗB
from pathlib import Path
path = Path(path) # '/dir0/dir1/somefile.txt'
print(f'path.stem: {path.stem}') # path.stem: somefile
print(f'path.suffix: {path.suffix}') # path.suffix: .txt
@ϐpathɂ͐قǂ̓ei'/dir0/dir1/somefile.txt'jPathNX̃IuWFNgɂ̂ĂBāAstem̓pX\ŏIvfisomefile.txtjgq菜̂ɂȂĂBɑāAsuffix͊gqɂȂĂB
@splitextł́upX̍\vfSĂgq́vƁugqvĂ̂ŁAPath.stem^Path.suffixsplitext̖߂lSɑΉĂ킯ł͂ȂƂɂ͒ӂ悤BlȌʂɂ́ApX\vf̂AŏIvfO̕\Path.parentgB
print(f'path.parent: {path.parent}') # path.parent: /dir0/dir1
@āAsplitextƓlȌʂɂ͈ȉ̂悤ɂ悢B
root = Path(f'{path.parent}/{path.stem}')
print(f'root: {root}, ext: {path.suffix}') # root: /dir0/dir1/somefile, ext: .txt
Copyright© Digital Advantage Corp. All Rights Reserved.