3

次のようなファイル パスを取得できる Python 関数を書きたいと思います。

/abs/path/to/my/file/file.txt

3 つの文字列変数を返します。

  • /abs- ルート ディレクトリと、パス内の「最上位」ディレクトリ
  • file- パスの「一番下」のディレクトリ。の親file.txt
  • path/to/my- パスの最上位ディレクトリと最下位ディレクトリの間のすべて

したがって、次の擬似コードを使用します。

def extract_path_segments(file):
    absPath = get_abs_path(file)
    top = substring(absPath, 0, str_post(absPath, "/", FIRST))
    bottom = substring(absPath, 0, str_post(absPath, "/", LAST))
    middle = str_diff(absPath, top, bottom)

    return (top, middle, bottom)

ここで助けてくれてありがとう!

4

4 に答える 4

5

を、さまざまなモジュール機能os.sepとともに探しています。os.pathその文字でパスを分割し、使用するパーツを再組み立てするだけです。何かのようなもの:

import os

def extract_path_segments(path, sep=os.sep):
    path, filename = os.path.split(os.path.abspath(path))
    bottom, rest = path[1:].split(sep, 1)
    bottom = sep + bottom
    middle, top = os.path.split(rest)
    return (bottom, middle, top)

これは、の両方が有効なパス区切り文字である Windows パスをうまく処理しません。その場合、ドライブ文字持っているので、とにかくそれも特別なケースにする必要があります.\ /

出力:

>>> extract_path_segments('/abs/path/to/my/file/file.txt')
('/abs', 'path/to/my', 'file')
于 2012-09-13T12:33:16.740 に答える
3

使用os.path.split:

import os.path

def split_path(path):
    """
    Returns a 2-tuple of the form `root, list_of_path_parts`
    """
    head,tail = os.path.split(path)
    out = []
    while tail:
        out.append(tail)
        head,tail = os.path.split(head)
    return head,list(reversed(out))

def get_parts(path):
    root,path_parts = split_path(path)
    head = os.path.join(root,path_parts[0])
    path_to = os.path.join(*path_parts[1:-2])
    parentdir = path_parts[-2]
    return head,path_to,parentdir

head,path_to,parentdir = get_parts('/foo/path/to/bar/baz')
print (head)        #foo
print (path_to)     #path/to
print (parentdir)   #bar
于 2012-09-13T12:44:55.043 に答える
2

os.path.split()andを使用os.path.join()する

>>> import os
>>> pth = "/abs/path/to/my/file/file.txt"
>>> parts = []
>>> while True:
...     pth, last = os.path.split(pth)
...     if not last:
...         break
...     parts.append(last)
...
>>> pth + parts[-1]
'/abs'
>>> parts[1]
'file'
>>> os.path.join(*parts[-2:1:-1])
'path/to/my'

機能として

import os

def extract_path_segments(pth):
    parts = []
    while True:
        pth, last = os.path.split(pth)
        if not last:
            break
        parts.append(last)
    return pth + parts[-1], parts[1], os.path.join(*parts[-2:1:-1])
于 2012-09-13T12:47:56.420 に答える
1
>>> p = '/abs/path/to/my/file/file.txt'
>>> r = p.split('/')
>>> r[1],'/'.join(r[2:-2]),r[-2]
('abs', 'path/to/my', 'file')
于 2012-09-13T12:48:29.897 に答える