Function in python that returns file extension
I am new to Python. I would like to understand the following function, which returns the extension of this file:
def get_extn(filename):
return filename[filename.rfind('.'):][1:]
I don't understand why there are parentheses in rfind [] but not () and why there are: and [1:] before the parenthesis. I appreciate the explanation.
source to share
What you see here is a function that has a two-fold slice syntax. For objects that support cut syntax, you can write:
object[f:t]
with indices f
and t
. Then you f
end up with a subsequence starting with and ending with t
( t
is exclusive). If f
or t
not specified, it usually means that we are cutting from start to finish.
The function in your question is a bit critical and is actually equivalent to:
def get_extn(filename):
f = filename.rfind('.')
filename = filename[f:]
return filename[1:]
So first we get the index of the last point, then we construct a substring that starts with f
, and finally we construct a substring from that substring that starts at index 1 (thus removing the first character that is '.'
).
source to share
You need to start by understanding python syntax.
The square brackets contain the accessors in the array, and the parentheses contain the function call. rfind is a function for which you enter the "." argument to find the period in the filename. the parentheses must extract elements in an array — both the elements in the filename and filename [], and elements from the array.
Colons,:, are slices within the array. [:] means the whole array, [1:] means the elements after the first. See Explain Fragment Notation
source to share
I suggest using the os.path module to handle filenames and paths.
Example:
import os.path
for path in ('/tmp/file.txt', 'file.doc', 'file', 'file.a.b.c'):
basename, extension=os.path.splitext(path)
print("path: '{}', base: '{}' extension '{}'".format(path,basename,extension))
Printing
path: '/tmp/file.txt', base: '/tmp/file' extension '.txt'
path: 'file.doc', base: 'file' extension '.doc'
path: 'file', base: 'file' extension ''
path: 'file.a.b.c', base: 'file.a.b' extension '.c'
source to share