2

I have a string from which I would like to extract certain part. The string looks like :

 E:/test/my_code/content/dir/disp_temp_2.hgx

This is a path on a machine for a specific file with extension hgx

I would exactly like to capture "disp_temp_2". The problem is that I used strip function, does not work for me correctly as there are many '/'. Another problem is that, that the above location will change always on the computer.

Is there any method so that I can capture the exact string between the last '/' and '.'

My code looks like:

path = path.split('.')

.. now I cannot split based on the last '/'.

Any ideas how to do this?

Thanks

6 Answers 6

6

Use the os.path module:

import os.path
filename = "E:/test/my_code/content/dir/disp_temp_2.hgx"
name = os.path.basename(filename).split('.')[0]
Sign up to request clarification or add additional context in comments.

2 Comments

Depends on what the user wants. The code above will turn something like foo.tar.gz into foo. This seems like the desired behavior. If someone has multiple dots in a filename like my.cool.file.txt then the convention becomes ambiguous and cannot be parsed without domain specific knowledge.
Thanks this works perfect for me. The file name that we has always one dot. That is before the extension.
3

Python comes with the os.path module, which gives you much better tools for handling paths and filenames:

>>> import os.path
>>> p = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> head, tail = os.path.split(p)
>>> tail
'disp_temp_2.hgx'
>>> os.path.splitext(tail)
('disp_temp_2', '.hgx')

Comments

1

Standard libs are cool:

>>> from os import path
>>> f = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> path.split(f)[1].rsplit('.', 1)[0]
'disp_temp_2'

Comments

0

Try this:

path=path.rsplit('/',1)[1].split('.')[0]

Comments

0

path = path.split('/')[-1].split('.')[0] works.

Comments

0

You can use the split on the other part :

path = path.split('/')[-1].split('.')[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.