Extract file name with the folder containing the file
If I have the following file path:
'G:\\My Drive\\A\\B\\C\\EH\\2021_12_17.txt'
How can I get the file name with the folder containing the file:
'EH\\2021_12_17.txt'
Solution 1:
You can apply pathlib
here:
from pathlib import Path
path = Path(r'G:\My Drive\A\B\C\EH\2021_12_17.txt')
result = path.relative_to(path.parents[1])
P.S. Use str()
if you need string result.
Solution 2:
Try join
with str.split
path = 'G:\\My Drive\\A\\B\\C\\EH\\2021_12_17.txt'
'\\'.join(path.split('\\')[-2:]) # -> 'EH\\2021_12_17.txt'