katericata
katericata

Reputation: 1058

Pythonic way to extract the file name and its parent directory from the full file path?

We have the full path of the file:

/dir1/dir2/dir3/sample_file.tgz

Basically, I would like to end up with this string:

dir3/sample_file.tgz

We can solve it with regex or with .split("/") and then take and concatenate the last two items in the list.....but I am wondering if we can do this more stylish with os.path.dirname() or something like that?

Upvotes: 4

Views: 2741

Answers (1)

dwanderson
dwanderson

Reputation: 2860

import os
full_filename = "/path/to/file.txt"
fname = os.path.basename(full_filename)
onedir = os.path.join(os.path.basename(os.path.dirname(full_filename)), os.path.basename(full_filename))

no one ever said os.path was pretty to use, but it ought to do the correct thing regardless of platform.

If you're in python3.4 (or higher, presumably), there's a pathlib:

import os
import pathlib
p = pathlib.Path("/foo/bar/baz/txt")
onedir = os.path.join(*p.parts[-2:])

Upvotes: 9

Related Questions