0

I'm opening texturepacks for my game and am holding filenames in a table, however when I use os.listdir() it returns the filenames with the extensions. Is there a way I could remove all characters after the dot that marks the file extension?

Example: Change 'Body.png' into 'Body' or 'Head.jpeg' into 'Head'

Thanks!

iPhynx
  • 443
  • 6
  • 11
  • Note, the first answer there is great except that they're using python2.x. For python3.x, you just need to use a `print` function. – mgilson Jun 06 '16 at 21:10

1 Answers1

3

You probably want os.path.splitext. It's useful for splitting file extensions out of filenames.

Here's an example:

>>> import os.path
>>> os.path.splitext('Body.png')
('Body', '.png')
>>> os.path.splitext('Body.png')[0]
'Body'
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • How would I use this. – iPhynx Jun 06 '16 at 21:07
  • or more simply >>> path = "c:/temp/x.txt" then split the path and take the first part... >>> path.split(".")[0] 'c:/temp/x' –  Jun 06 '16 at 21:11
  • 1
    @DanPatterson -- But quite possibly wrong... What if you have a filename: `path = 'c:/temp.foo/x.txt'`? I suppose that `path.rsplit(".", 1)[0]` is maybe more robust? But I'd rather rely on a library function that is meant to handle all of these weird corner cases... – mgilson Jun 06 '16 at 21:14
  • @mgilson You are quite right with the `rsplit`. It's more correct. Nevertheless, apart from the robustness of a library it's also semantically much clearer to use `os.path.splitext`. – Tim Hoffmann Jun 06 '16 at 21:17
  • @TimHoffmann -- Yep, I definitely agree. Semantics are more important than people give them credit for I think ... – mgilson Jun 06 '16 at 21:18
  • Good point, I have never used "." in folder names, I just got into the habit of using raw notation and "_" instead of spaces, perhaps for that reason. –  Jun 06 '16 at 21:36
  • Rsplit worked great for me. Thanks @mgilson. – iPhynx Jun 06 '16 at 21:43