averyrc
averyrc

Reputation: 25

Using os.path.splitext to seperate filename and extension

I am creating a program in which I need to separate the file name and the file extension of a fle. The way i am doing this is by using

os.path.splitext('')

I was simply wondering if anybody knows how I could save the two parts of the file as two variables.

Upvotes: 0

Views: 4678

Answers (1)

Mike Müller
Mike Müller

Reputation: 85622

os.path.splitext() returns a tuple:

>>> import os
>>> name_parts = os.path.splitext('data.txt')
>>> name_parts 
('data', '.txt')

You can take it apart:

>>> body, ext = name_parts

Now:

>>> body
'data'

and:

>>> ext
'.txt'

You can do this in one step:

>>> body, ext = os.path.splitext('data.txt')

This is called tuple unpacking.

​For example:

>>> a = 1
>>> b = 2

You can swap their values with:

>>> a, b = b, a

You can also place parenthesis around. It is not necessary but may help to understand what is going on:

>>> (a, b) = (b, a)

Upvotes: 6

Related Questions