0

I have the following link: '//mypath/link1/link2/link3/link4/this is the folder\\123456 (2).txt'

I would like to extract the path+sub directory separately, filename with extension and filename without extension. The output should look like the following:

[//mypath/link1/link2/link3/link4/this is the folder, 123456 (2).txt, 123456]

What I tried so far?

import os
pth = '//mypath/link1/link2/link3/link4/this is the folder\\123456 (2).txt'
head, tail = os.path.split(pth)
print([head, tail])

I was able to extract the path and filename but not the filename without extension. How do I do that?

blondelg
  • 916
  • 1
  • 8
  • 25
disukumo
  • 321
  • 6
  • 15
  • 1
    Does this answer your question? [Extracting extension from filename in Python](https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python) – sushanth May 26 '21 at 09:42
  • No, it extracts the file extensions and not the filename. Thanks for the suggestion :) – disukumo May 26 '21 at 09:46

1 Answers1

1

You can use string.split() two times.

pth = '//mypath/link1/link2/link3/link4/this is the folder\\123456 (2).txt'
path,filename = pth.split('\\')
file_no_ex = filename.split(' ')[0]
output = [path,filename,file_no_ex]

Output:

['//mypath/link1/link2/link3/link4/this is the folder', '123456 (2).txt', '123456']

Trong Van
  • 374
  • 1
  • 13