Python: cut equivalent in Python?
Question: I want to parse a path (not filename) by the forward slash. Below takes the
full path "filename" and reads up to the 7th "/".

**EDIT: I realized the above was confusing when I stated filename. I meant, I
needed to parse the full path. e.g. I could need the first 7 "/"s to the left
and remove 5 trailing "/"s.**

Python:

    
    
    "/".join(filename.split("/")[:7])
    

Bash:

    
    
    some command that prints filename | cut -d'/' -f1-7`
    

It looks so much cleaner with the cut tool. Is there a better/ more efficient
way to write this in Python?


Answer: Usually I would recommend using functions from the
[`os.path`](http://docs.python.org/3/library/os.path.html) module for handling
paths. I prefer to let the library handle all of the edge cases that can occur
with valid paths.

As was you pointed out in the comments,
[`os.path.split()`](http://docs.python.org/3/library/os.path.html#os.path.split)
splits just the last path element. To use it, one could write:

    
    
    l = []
    while True:
        head, tail = os.path.split(filename)
        l.insert(0, tail)
        if head == "/":
            l.insert(0, "")
            break
        filename = head
    "/".join(l[:7])
    

Although more verbose, this will correctly normalize artifacts such as
duplicate slashes.

On the other hand, your use of `string.split()` matches the semantics of
`cut(1)`.

* * *

Sample test cases:

    
    
    $ echo '/a/b/c/d/e/f/g/h' | cut -d'/' -f1-7 
    /a/b/c/d/e/f
    
    $ echo '/a/b/c/d/e/f/g/h/' | cut -d'/' -f1-7 
    /a/b/c/d/e/f
    
    $ echo '/a//b///c/d/e/f/g/h' | cut -d'/' -f1-7
    /a//b///c
    

* * *
    
    
    # Tests and comparison to string.split()
    
    import os.path
    
    def cut_path(filename):
        l = []
        while True:
            head, tail = os.path.split(filename)
            l.insert(0, tail)
            if head == "/":
                l.insert(0, "")
                break
            filename = head
        return "/".join(l[:7])
    
    def cut_string(filename):
        return "/".join( filename.split("/")[:7] )
    
    def test(filename):
        print("input:", filename)
        print("string.split:", cut_string(filename))
        print("os.path.split:", cut_path(filename))
        print()
    
    test("/a/b/c/d/e/f/g/h")
    test("/a/b/c/d/e/f/g/h/")
    test("/a//b///c/d/e/f/g/h")
    
    # input: /a/b/c/d/e/f/g/h
    # string.split: /a/b/c/d/e/f
    # os.path.split: /a/b/c/d/e/f
    #
    # input: /a/b/c/d/e/f/g/h/
    # string.split: /a/b/c/d/e/f
    # os.path.split: /a/b/c/d/e/f
    #
    # input: /a//b///c/d/e/f/g/h
    # string.split: /a//b///c
    # os.path.split: /a/b/c/d/e/f
    

