Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 903
katericata Avatar asked Sep 19 '25 17:09

katericata


1 Answers

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:])
like image 64
dwanderson Avatar answered Sep 22 '25 07:09

dwanderson