0

How can I strip the directory and filename out from a full path given to me as a string?

For example, from:

>>path_string
C:/Data/Python/Project/Test/file.txt

I want to get:

>>dir_and_file_string
Test/file.txt

I'm assuming that this is a string operation rather than a filesystem operation.

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • If its just string operation, just split on "/", get the last 2 elements and join them with "/" again. Or you can use `os.path.sep` as the path separator. – ghostdog74 Oct 30 '14 at 07:13
  • You should give some details on the origin of the base path, how platform independent you are, etc. It can be done through regular expressions or through something more OS-aware (e.g. how should it behave on a string like ``C:/Path/To/../Strange/../Folder``?) – MariusSiuram Oct 30 '14 at 07:27

4 Answers4

1

Not overly elegant, but here goes:

In [7]: path = "C:/Data/Python/Project/Test/file.txt"

In [8]: dir, filename = os.path.split(path)

In [9]: dir_and_file_string = os.path.join(os.path.split(dir)[1], filename)

In [10]: dir_and_file_string
Out[10]: 'Test/file.txt'

This is verbose, but is portable and robust.

Alternatively, you could treat this as a string operation:

In [16]: '/'.join(path.split('/')[-2:])
Out[16]: 'Test/file.txt'

but be sure to read why use os.path.join over string concatenation. For example, this fails if the path contains backslashes (which is the traditional path separator on Windows). Using os.path.sep instead of '/' won't solve this problem entirely.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You should use os.path.relpath

import os
full_path = "/full/path/to/file"
base_path = "/full/path"
relative_path = os.path.relpath(full_path, base_path)
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • IMO for this to be a complete solution, you need to programmatically derive `base_path` from `full_path` instead of hard-coding it. – NPE Oct 30 '14 at 07:22
  • If you programatically derive ``base_path`` from ``full_path`` or viceversa, then you don't need to get the relative path because you programatically know it. I understand it as a good illustrative example. The question lacks some details. – MariusSiuram Oct 30 '14 at 07:25
0
os.path.sep.join(path_string.split(os.path.sep)[-2:])
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

Little round about solution I guess but it works fine.

path_string = "C:/Data/Python/Project/Test/file.txt"
_,_,_,_,dir_,file1, = path_string.split("/")
dir_and_file_string = dir_+"/"+file1
print dir_and_file_string
d-coder
  • 12,813
  • 4
  • 26
  • 36