2

I am getting a huge .txt which I need to slice, save all sliced files in a new directory which at the end of using, I delete.

Now to make a new dir I need path to dir. I want to save in the same dir given by user where he points to a .txt file.

def retPath(path):
    name = path.split('/')
    k = len(name)
    p = ""
    for i in range (0, k-1):
        if i == 0:
            p = p + name[i]
        else:
            p = p + '/' + name[i]
    return p


print(retPath('C:/dir1/dic2/file.txt'))

OUTPUT:

C:/dir1/dic2

This works but I wonder if there's a more pythonic way to do it.

1 Answer 1

1

Look at os.path.dirname:

>>> p = '/Users/user/Desktop/words.py'
>>> os.path.dirname(p)
'/Users/user/Desktop'
Sign up to request clarification or add additional context in comments.

1 Comment

This returns None. Edit: forgot to return in my function. AWESOME! thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.