Is there a function to extract the extension from a filename?
33 Answers
Use os.path.splitext
:
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
Unlike most manual string-splitting attempts, os.path.splitext
will correctly treat /a/b.c/d
as having no extension instead of having extension .c/d
, and it will treat .bashrc
as having no extension instead of having extension .bashrc
:
>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')

- 24,552
- 19
- 101
- 135

- 217,122
- 57
- 293
- 297
-
22the use of `basename` is a little confusing here since `os.path.basename("/path/to/somefile.ext")` would return `"somefile.ext"` – Jiaaro Sep 19 '11 at 21:35
-
2see also ideas below concerning `lower()` and double extensions – Antony Hatchkins Feb 13 '13 at 10:24
-
21wouldn't `endswith()` not be more portable and pythonic? – Sebastian Mach Aug 28 '13 at 16:42
-
8You can't rely on that if you have files with "double extensions", like `.mp3.asd` for example, because it will return you only the "last" extension! – klingt.net Jan 09 '14 at 11:15
-
86@klingt.net Well, in that case, `.asd` is really the extension!! If you think about it, `foo.tar.gz` is a **gzip-compressed file** (`.gz`) which happens to be a **tar file** (`.tar`). But it is a **gzip file** in first place. I wouldn't expect it to return the dual extension at all. – nosklo Jan 16 '14 at 20:18
-
234The standard Python function naming convention is really annoying - almost every time I re-look this up, I mistake it as being `splittext`. If they would just do anything to signify the break between parts of this name, it'd be much easier to recognize that it's `splitExt` or `split_ext`. Surely I can't be the only person who has made this mistake? – ArtOfWarfare Jan 07 '15 at 23:27
-
1a tuple is returned and if you want to get the extension use: `file_extension=os.path.splitext('/path/to/somefile.ext')[1]` or if you want the filename use: `filename=os.path.splitext('/path/to/somefile.ext')[0]` – Jan Mar 01 '17 at 20:51
-
2@ArtOfWarfare Given the small size of the `os.path` submodule, you could conceivably remap the names manually in your own module saved on your Python path. E.g. `myospath.py` containing things like `splitExt = os.path.splitext`. – Jonathan H Mar 12 '18 at 13:30
-
Despite not answering to the OP, it would be a great improvement if you also provide the opposite solution. Or a link for it. When I am saying the opposite, I am referring to now the filename with no extension. – Francisco Maria Calisto May 08 '19 at 15:59
-
1@FranciscoMariaCalisto I'm not sure what you mean. There is already one example of a file without extension in the answer, the `/a/b.c/d` file. If by "opposite" of splitting you mean joining the filename with an extension, that can be done by normal concatenation: `filename + file_extension` – nosklo May 08 '19 at 16:22
-
1If you just need the extension, without the `.` prefixed, use `os.path.splitext('filename.ext')[1][1:]`. Obvious but just a reminder for those of us who like to code mainly using [ctrl]+C/V. – Chris Apr 28 '20 at 13:14
New in version 3.4.
import pathlib
print(pathlib.Path('yourPath.example').suffix) # '.example'
print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz']
print(pathlib.Path('/foo/bar.txt').stem) # 'bar'
I'm surprised no one has mentioned pathlib
yet, pathlib
IS awesome!
-
31example for getting .tar.gz: `''.join(pathlib.Path('somedir/file.tar.gz').suffixes)` – teichert Aug 03 '17 at 18:15
-
Great answer. I found this tutorial more useful than the documentation: http://zetcode.com/python/pathlib/ – user118967 Sep 11 '19 at 02:38
-
3@user3780389 Wouldn't a "foo.bar.tar.gz" still be a valid ".tar.gz"? If so your snippet should be using `.suffixes[-2:]` to ensure only getting .tar.gz at most. – jeromej Apr 20 '20 at 07:25
-
there are still cases when this does not work as expected like `"filename with.a dot inside.tar"`. This is the solution i am using currently: `"".join([s for s in pathlib.Path('somedir/file.tar.gz').suffixes if not " " in s])` – eadmaster Jan 02 '21 at 19:09
import os.path
extension = os.path.splitext(filename)[1]

- 31,821
- 7
- 55
- 59
-
26Out of curiosity, why `import os.path` instead of `from os import path`? – kiswa Aug 26 '11 at 12:40
-
1@kiswa - I suppose you could do it that way. I've seen more code using `import os.path` though. – Brian Neal Aug 26 '11 at 19:01
-
78it depends really, if you use `from os import path` then the name `path` is taken up in your local scope, also others looking at the code may not immediately know that path is the path from the os module. Where as if you use `import os.path` it keeps it within the `os` namespace and wherever you make the call people know it's `path()` from the `os` module immediately. – dennmat Nov 24 '11 at 18:45
-
1but what's the point of importing `os.path` if we could just `import os`? – Ivan Virabyan Feb 09 '12 at 07:06
-
1@IvanVirabyan See this question: http://stackoverflow.com/questions/2724348/should-i-use-import-os-path-or-import-os – Brian Neal Feb 10 '12 at 16:56
-
29I know it's not semantically any different, but I personally find the construction `_, extension = os.path.splitext(filename)` to be much nicer-looking. – Tim Gilbert Aug 14 '14 at 03:37
-
1@TimGilbert Hmm... same exact number of characters, but I feel `_, ` is less heavy/distracting than `[1]`, and maybe even a bit clearer. I ran both through `timeit`... your form takes between 2.02 usec and 2.04 usec on my computer, while the form in this answer takes between 2.04 usec and 2.06 usec. So performance is infinitesimally improved at best, or the exact same at worse. I can't come up with any reason to not use your form. – ArtOfWarfare Mar 12 '16 at 13:38
-
3If you want the extension as part of a more complex expression the [1] may be more useful: `if check_for_gzip and os.path.splitext(filename)[1] == '.gz':` – gerardw Feb 20 '18 at 19:38
-
@kiswa The docs literally say to just import os: `help(os.path) -> "Instead of importing this module directly, import os and refer to this module as os.path."` – SurpriseDog Apr 11 '21 at 16:01
-
Make sure to append `[1:]` to the result, to remove the leading dot since that's not part of the extension: https://en.wikipedia.org/wiki/Filename_extension – Raleigh L. Jun 24 '22 at 06:15
import os.path
extension = os.path.splitext(filename)[1][1:]
To get only the text of the extension, without the dot.
-
1This will return empty for both file names end with `.` and file names without an extension. – user202729 Dec 12 '20 at 16:11
For simple use cases one option may be splitting from dot:
>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'
No error when file doesn't have an extension:
>>> "filename".split(".")[-1]
'filename'
But you must be careful:
>>> "png".split(".")[-1]
'png' # But file doesn't have an extension
Also will not work with hidden files in Unix systems:
>>> ".bashrc".split(".")[-1]
'bashrc' # But this is not an extension
For general use, prefer os.path.splitext

- 8,207
- 5
- 53
- 78
-
5
-
22Not actually. Extension of a file named "x.tar.gz" is "gz" not "tar.gz". os.path.splitext gives ".os" as extension too. – Murat Çorlu May 11 '12 at 20:21
-
This works when you are processing files for platforms other than the one you run. – Himanshu Apr 15 '13 at 06:28
-
2can we use [1] rather than [-1]. I could not understand [-1] with split – user765443 Aug 21 '13 at 05:44
-
11[-1] to get last item of items that splitted by dot. Example: `"my.file.name.js".split('.') => ['my','file','name','js]` – Murat Çorlu Aug 21 '13 at 08:27
-
@MuratÇorlu `rsplit[1]` is the better approach for this. I agree with you, though, the LAST extension represents the current wrapper or encoding of the file. `myfile.tar.gz` is a gzipped file _before_ it is a tar. – Benjamin R Aug 24 '17 at 21:40
-
@MuratÇorlu Whoops: `rsplit('.', 1)` is what I meant! Then you check if the length of the list being returned is > 1 or not as a test. – Benjamin R Aug 24 '17 at 23:50
-
@BenjaminR I couldn't get the motivation behind using `rsplit` instead of `split` for this case. `rsplit('.', 1)` also returns an array. So again you'll need to get last item of that array to get extension only, right? Also you can check the length of the array that `split` produce to test it has an extension or not. – Murat Çorlu Aug 25 '17 at 09:59
-
@MuratÇorlu The return value from `rsplit` in this case is more reflective of what your intent is. You only care about what's split on the last period, not any other periods. Why have a list (it's not an array fyi) with bits you don't care about? You only care about what's before and after that last period. – Benjamin R Aug 28 '17 at 06:20
-
2@BenjaminR ah ok, you are making an optimisation about result list. `['file', 'tar', 'gz']` with `'file.tar.gz'.split('.')` **vs** `['file.tar', 'gz']` with `'file.tar.gz'.rsplit('.', 1)`. yeah, could be. – Murat Çorlu Aug 28 '17 at 08:44
-
just a heads up, this method fails if you have any directories in here that have `.` in them along with an extensionless file (which both are common in a *nix env) `"/home/example/.config/README".split(".")[-1] == ".config/README"` – Seaux Jun 11 '20 at 21:46
-
@Seaux Good point but question is about "extracting extension from filename". What is the extension of README? So, if there is no extension, yes, this method will not work. To avoid the situation about directory names, a solution can be first find the "filename" from full path. – Murat Çorlu Jun 12 '20 at 22:05
-
1@MuratÇorlu The extension of `README` is `""` because it has no extension. Whereas with this solution the extension of `README` would be `README` -- which is wrong. That does appear already stated in the answer though -- I just wanted to also point out the condition with directories. – Seaux Jun 13 '20 at 03:05
worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.
os.path.splitext(filename)[1][1:].strip().lower()

- 2,699
- 2
- 23
- 17
-
The `strip()` will break in rare edge-cases where the filename extension includes whitespace. – Flimm Apr 29 '23 at 09:22
-
Some filesystems are case-sensitive (like the ones on Linux), and even NTFS is case-sensitive, although Windows tries to treat it in a case-insensitive manner. Be careful with case. – Flimm Apr 29 '23 at 09:23
With splitext there are problems with files with double extension (e.g. file.tar.gz
, file.tar.bz2
, etc..)
>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension
'.gz'
but should be: .tar.gz
The possible solutions are here
-
1
-
1
-
1This is why we have the extension 'tgz' which means: tar+gzip ! :D – Nuno Aniceto Sep 21 '14 at 23:07
-
@FlipMcF The filename should obviously be `somefile.tar`. For `tar -xzvf somefile.tar.gz` the filename should be `somefile`. – peterhil Oct 12 '14 at 18:51
-
1@peterhil I don't think you want your python script to be aware of the application used to create the filename. It's a bit out of scope of the question. Don't pick on the example, 'filename.csv.gz' is also quite valid. – FlipMcF Oct 15 '14 at 21:10
You can find some great stuff in pathlib module (available in python 3.x).
import pathlib
x = pathlib.PurePosixPath("C:\\Path\\To\\File\\myfile.txt").suffix
print(x)
# Output
'.txt'

- 579
- 6
- 12
Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the strip()
method to the end. For example:
import os.path
extension = os.path.splitext(filename)[1][1:].strip()

- 35,843
- 15
- 128
- 182

- 237
- 2
- 2
-
1To aid my understanding, please could you explain what additional behaviour the second index/slice guards against? (i.e. the `[1:]` in `.splittext(filename)[1][1:]`) - thank you in advance – Samuel Harmer Oct 11 '11 at 09:47
-
1Figured it out for myself: `splittext()` (unlike if you split a string using '.') includes the '.' character in the extension. The additional `[1:]` gets rid of it. – Samuel Harmer Oct 11 '11 at 09:55
-
This will break if the file extension contains whitespace. That's a rare case, I know, but it's still an edge-case that should be considered. – Flimm Apr 29 '23 at 09:22
Just join
all pathlib suffixes
.
>>> x = 'file/path/archive.tar.gz'
>>> y = 'file/path/text.txt'
>>> ''.join(pathlib.Path(x).suffixes)
'.tar.gz'
>>> ''.join(pathlib.Path(y).suffixes)
'.txt'

- 1,221
- 2
- 26
- 42
Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case:
to get extension of a given file absolute path, you can simply type:
filepath.rpartition('.')[-1]
example:
path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]
will give you: 'csv'

- 551
- 5
- 6
-
2For those not familiar with the API, [rpartition](https://docs.python.org/3/library/stdtypes.html#str.rpartition) returns a tuple: `("string before the right-most occurrence of the separator", "the separator itself", "the rest of the string")`. If there's no separator found, the returned tuple will be: `("", "", "the original string")`. – Nickolay May 26 '18 at 22:03
Surprised this wasn't mentioned yet:
import os
fn = '/some/path/a.tar.gz'
basename = os.path.basename(fn) # os independent
Out[] a.tar.gz
base = basename.split('.')[0]
Out[] a
ext = '.'.join(basename.split('.')[1:]) # <-- main part
# if you want a leading '.', and if no result `None`:
ext = '.' + ext if ext else None
Out[] .tar.gz
Benefits:
- Works as expected for anything I can think of
- No modules
- No regex
- Cross-platform
- Easily extendible (e.g. no leading dots for extension, only last part of extension)
As function:
def get_extension(filename):
basename = os.path.basename(filename) # os independent
ext = '.'.join(basename.split('.')[1:])
return '.' + ext if ext else None

- 20,643
- 17
- 103
- 160
-
2This results in an exception when the file doesn't have any extension. – thiruvenkadam Apr 01 '16 at 13:42
-
7This answer absolutely ignore a variant if a filename contains many points in name. Example get_extension('cmocka-1.1.0.tar.xz') => '.1.0.tar.xz' - wrong. – PADYMKO Dec 29 '16 at 08:46
-
@PADYMKO, IMHO one should not create filenames with full stops as part of the filename. The code above is not supposed to result in 'tar.xz' – Douwe van der Leest Dec 13 '19 at 09:01
-
2
You can use a split
on a filename
:
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
This does not require additional library

- 7,016
- 8
- 29
- 37

- 594
- 3
- 7
- 24
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]

- 143
- 1
- 3
-
2This results in the last char of `filename` being returned if the filename has no `.` at all. This is because `rfind` returns `-1` if the string is not found. – mattst Jul 25 '16 at 11:33
Extracting extension from filename in Python
Python os module splitext()
splitext() function splits the file path into a tuple having two values – root and extension.
import os
# unpacking the tuple
file_name, file_extension = os.path.splitext("/Users/Username/abc.txt")
print(file_name)
print(file_extension)
Get File Extension using Pathlib Module
Pathlib module to get the file extension
import pathlib
pathlib.Path("/Users/pankaj/abc.txt").suffix
#output:'.txt'

- 1,069
- 6
- 13
Even this question is already answered I'd add the solution in Regex.
>>> import re
>>> file_suffix = ".*(\..*)"
>>> result = re.search(file_suffix, "somefile.ext")
>>> result.group(1)
'.ext'

- 79
- 1
- 4
-
2Or `\.[0-9a-z]+$` as in [this post](https://stackoverflow.com/questions/6582171/javascript-regex-for-matching-extracting-file-extension). – pault Mar 19 '18 at 16:02
This is a direct string representation techniques : I see a lot of solutions mentioned, but I think most are looking at split. Split however does it at every occurrence of "." . What you would rather be looking for is partition.
string = "folder/to_path/filename.ext"
extension = string.rpartition(".")[-1]

- 662
- 4
- 11
-
4rpartition was already suggested by [@weiyixie](https://stackoverflow.com/a/42477550/1026). – Nickolay May 26 '18 at 22:04
Another solution with right split:
# to get extension only
s = 'test.ext'
if '.' in s: ext = s.rsplit('.', 1)[1]
# or, to get file name and extension
def split_filepath(s):
"""
get filename and extension from filepath
filepath -> (filename, extension)
"""
if not '.' in s: return (s, '')
r = s.rsplit('.', 1)
return (r[0], r[1])

- 1,100
- 14
- 14
you can use following code to split file name and extension.
import os.path
filenamewithext = os.path.basename(filepath)
filename, ext = os.path.splitext(filenamewithext)
#print file name
print(filename)
#print file extension
print(ext)

- 3,894
- 22
- 31

- 85
- 1
- 7
A true one-liner, if you like regex. And it doesn't matter even if you have additional "." in the middle
import re
file_ext = re.search(r"\.([^.]+)$", filename).group(1)
See here for the result: Click Here

- 12,464
- 7
- 65
- 73

- 765
- 12
- 26
You can use endswith to identify the file extension in python
like bellow example
for file in os.listdir():
if file.endswith('.csv'):
df1 =pd.read_csv(file)
frames.append(df1)
result = pd.concat(frames)

- 405
- 4
- 5
Well , i know im late
that's my simple solution
file = '/foo/bar/whatever.ext'
extension = file.split('.')[-1]
print(extension)
#output will be ext

- 134
- 1
- 5
-
@NsaNinja but the malware.pdf.exe is [exe] type ! also for tar.gz ! – Waleed Khaled Nov 05 '22 at 12:46
-
1I agree that there are drawbacks for completeness, HOWEVER, this is a "simple" solution and for simple uses it works. In my case, for example, I've already confirmed that the file exists and is one of several filtered file types. I just need to know which one. For that application, this works. – BSD Nov 15 '22 at 17:40
try this:
files = ['file.jpeg','file.tar.gz','file.png','file.foo.bar','file.etc']
pen_ext = ['foo', 'tar', 'bar', 'etc']
for file in files: #1
if (file.split(".")[-2] in pen_ext): #2
ext = file.split(".")[-2]+"."+file.split(".")[-1]#3
else:
ext = file.split(".")[-1] #4
print (ext) #5
- get all file name inside the list
- splitting file name and check the penultimate extension, is it in the pen_ext list or not?
- if yes then join it with the last extension and set it as the file's extension
- if not then just put the last extension as the file's extension
- and then check it out

- 221
- 3
- 6
-
2This breaks for a bunch of special cases. See the accepted answer. It's reinventing the wheel, only in a buggy way. – Robert Apr 20 '20 at 23:59
-
Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 21 '20 at 00:34
-
-
You're only making it worse, breaking it in new ways. `foo.tar` is a valid file name. What happens if I throw that at your code? What about `.bashrc` or `foo`? There is a library function for this for a reason... – Robert Apr 21 '20 at 01:25
-
just create a list of extension file for the penultimate extension, if not in list then just put the last extension as the file's extension – Ibnul Husainan Apr 21 '20 at 06:45
The easiest way to get is to use mimtypes, below is the example:
import mimetypes
mt = mimetypes.guess_type("file name")
file_extension = mt[0]
print(file_extension)

- 247
- 10
- 26
I'm definitely late to the party, but in case anyone wanted to achieve this without the use of another library:
file_path = "example_tar.tar.gz"
file_name, file_ext = [file_path if "." not in file_path else file_path.split(".")[0], "" if "." not in file_path else file_path[file_path.find(".") + 1:]]
print(file_name, file_ext)
The 2nd line is basically just the following code but crammed into one line:
def name_and_ext(file_path):
if "." not in file_path:
file_name = file_path
else:
file_name = file_path.split(".")[0]
if "." not in file_path:
file_ext = ""
else:
file_ext = file_path[file_path.find(".") + 1:]
return [file_name, file_ext]
Even though this works, it might not work will all types of files, specifically .zshrc
, I would recomment using os
's os.path.splitext
function, example below:
import os
file_path = "example.tar.gz"
file_name, file_ext = os.path.splitext(file_path)
print(file_name, file_ext)
Cheers :)

- 678
- 3
- 20
For funsies... just collect the extensions in a dict, and track all of them in a folder. Then just pull the extensions you want.
import os
search = {}
for f in os.listdir(os.getcwd()):
fn, fe = os.path.splitext(f)
try:
search[fe].append(f)
except:
search[fe]=[f,]
extensions = ('.png','.jpg')
for ex in extensions:
found = search.get(ex,'')
if found:
print(found)

- 3,809
- 1
- 14
- 20
-
That's a terrible idea. Your code breaks for any file extension you haven't previously added! – Robert Apr 21 '20 at 00:02
This method will require a dictonary, list, or set. you can just use ".endswith" using built in string methods. This will search for name in list at end of file and can be done with just str.endswith(fileName[index])
. This is more for getting and comparing extensions.
https://docs.python.org/3/library/stdtypes.html#string-methods
Example 1:
dictonary = {0:".tar.gz", 1:".txt", 2:".exe", 3:".js", 4:".java", 5:".python", 6:".ruby",7:".c", 8:".bash", 9:".ps1", 10:".html", 11:".html5", 12:".css", 13:".json", 14:".abc"}
for x in dictonary.values():
str = "file" + x
str.endswith(x, str.index("."), len(str))
Example 2:
set1 = {".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"}
for x in set1:
str = "file" + x
str.endswith(x, str.index("."), len(str))
Example 3:
fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
for x in range(0, len(fileName)):
str = "file" + fileName[x]
str.endswith(fileName[x], str.index("."), len(str))
Example 4
fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
str = "file.txt"
str.endswith(fileName[1], str.index("."), len(str))
Example 8
fileName = [".tar.gz", ".txt", ".exe", ".js", ".java", ".python", ".ruby", ".c", ".bash", ".ps1", ".html", ".html5", ".css", ".json", ".abc"];
exts = []
str = "file.txt"
for x in range(0, len(x)):
if str.endswith(fileName[1]) == 1:
exts += [x]

- 41
- 6
Here if you want to extract the last file extension if it has multiple
class functions:
def listdir(self, filepath):
return os.listdir(filepath)
func = functions()
os.chdir("C:\\Users\Asus-pc\Downloads") #absolute path, change this to your directory
current_dir = os.getcwd()
for i in range(len(func.listdir(current_dir))): #i is set to numbers of files and directories on path directory
if os.path.isfile((func.listdir(current_dir))[i]): #check if it is a file
fileName = func.listdir(current_dir)[i] #put the current filename into a variable
rev_fileName = fileName[::-1] #reverse the filename
currentFileExtension = rev_fileName[:rev_fileName.index('.')][::-1] #extract from beginning until before .
print(currentFileExtension) #output can be mp3,pdf,ini,exe, depends on the file on your absolute directory
Output is mp3, even works if has only 1 extension name

- 69,221
- 14
- 89
- 114

- 11
- 2
# try this, it works for anything, any length of extension
# e.g www.google.com/downloads/file1.gz.rs -> .gz.rs
import os.path
class LinkChecker:
@staticmethod
def get_link_extension(link: str)->str:
if link is None or link == "":
return ""
else:
paths = os.path.splitext(link)
ext = paths[1]
new_link = paths[0]
if ext != "":
return LinkChecker.get_link_extension(new_link) + ext
else:
return ""

- 6,899
- 9
- 48
- 67

- 105
- 1
- 4
a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1]) # bashrc
print(extension_b[-1]) # txt

- 332
- 4
- 5
-
Please add explanation of the code, rather than simply just the code snippets. – Audwin Oyong Sep 08 '21 at 23:55
def NewFileName(fichier):
cpt = 0
fic , *ext = fichier.split('.')
ext = '.'.join(ext)
while os.path.isfile(fichier):
cpt += 1
fichier = '{0}-({1}).{2}'.format(fic, cpt, ext)
return fichier

- 3,873
- 1
- 16
- 37
This is The Simplest Method to get both Filename & Extension in just a single line.
fName, ext = 'C:/folder name/Flower.jpeg'.split('/')[-1].split('.')
>>> print(fName)
Flower
>>> print(ext)
jpeg
Unlike other solutions, you don't need to import any package for this.

- 197
- 1
- 1
- 7
name_only=file_name[:filename.index(".")
That will give you the file name up to the first ".", which would be the most common.

- 158,662
- 42
- 215
- 303

- 329
- 1
- 5
- 13
-
1first, he needs not the name, but extension. Second, even if he would need name, it would be wrong by files like: `file.name.ext` – ya_dimon Nov 04 '15 at 18:13
-
As mentioned by @ya_dimon, this wont work for files names with dots. Plus, he needs the extension! – Umar Dastgir May 29 '19 at 17:38