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.