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!

1
  • 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. Commented Jun 6, 2016 at 21:10

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

7 Comments

How would I use this.
or more simply >>> path = "c:/temp/x.txt" then split the path and take the first part... >>> path.split(".")[0] 'c:/temp/x'
@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 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.
@TimHoffmann -- Yep, I definitely agree. Semantics are more important than people give them credit for I think ...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.