0

I basically want to call only the part of my string that falls before the "."

For example, if my filename is sciPHOTOf105w0.fits, I want to call "sciPHOTOf105w" as its own string so that I can use it to name a new file that's related to it. How do you do this? I can't just use numeral values "ex. if my file name is 'file', file[5:10]." I need to be able to collect everything up to the dot without having to count, because the file names can be of different lengths.

1
  • 1
    I think that you should really consider accepting one of the splitext() solutions: they handle all cases gracefully (no dot at all in the path, or multiple dots): this will direct people who have the same question as you to more robust and relevant answers. Commented Jul 19, 2013 at 3:25

4 Answers 4

4

You can also use os.path like so:

>>> from os.path import splitext
>>> splitext('sciPHOTOf105w0.fits') # separates extension from file name
('sciPHOTOf105w0', '.fits')
>>> splitext('sciPHOTOf105w0.fits')[0]
'sciPHOTOf105w0'

If your file happens to have a longer path, this approach will also account for your full path.

Sign up to request clarification or add additional context in comments.

1 Comment

And if the directory part has a period but the filename doesn't, it will still do the right thing.
2
import os.path
filename = "sciPHOTOf105w0.fits"

root, ext = os.path.splitext(filename)
print "root is: %s" % root
print "ext is: %s" % ext

result:

>root is: sciPHOTOf105w0
>ext is: .fits

Comments

1
In [33]: filename = "sciPHOTOf105w0.fits"

In [34]: filename.rpartition('.')[0]
Out[34]: 'sciPHOTOf105w0'

In [35]: filename.rsplit('.', 1)[0]
Out[35]: 'sciPHOTOf105w0'

3 Comments

What if the filename is 'my.files\\sciPHOTOf105w0'?
@MarkRansom: in that case, there is no extension, and my code will break. Someone else used os.splittext, which will handle this case.
Why mention rpartition() when the separator is not needed? it strikes me as doing too much work for what is needed (no need for three strings, two are enough, as with rsplit(…, 1) and friends).
0

You can use .index() on a string to find the first occurence of a substring.

>>> filename = "sciPHOTOf105w0.fits"
>>> filename.index('.')
14
>>> filename[:filename.index('.')]
'sciPHOTOf105w0'

1 Comment

Since the goal is to remove the extension, os.path.splittext() is more appropriate (it works even if the path contains no or multiple dots).

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.