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.
4 Answers 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.
1 Comment
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
In [33]: filename = "sciPHOTOf105w0.fits"
In [34]: filename.rpartition('.')[0]
Out[34]: 'sciPHOTOf105w0'
In [35]: filename.rsplit('.', 1)[0]
Out[35]: 'sciPHOTOf105w0'
3 Comments
'my.files\\sciPHOTOf105w0'?os.splittext, which will handle this case.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).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
os.path.splittext() is more appropriate (it works even if the path contains no or multiple dots).
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.