Karnivaurus
Karnivaurus

Reputation: 24111

Stripping directory and filename from path as a string

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.

Upvotes: 0

Views: 2102

Answers (4)

ghostdog74
ghostdog74

Reputation: 342273

os.path.sep.join(path_string.split(os.path.sep)[-2:])

Upvotes: 0

d-coder
d-coder

Reputation: 13943

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

Upvotes: 0

NPE
NPE

Reputation: 500167

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.

Upvotes: 1

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

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)

Upvotes: 1

Related Questions