Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file extension correctly?

Tags:

python

I know that this question is asked many times on this website. But I found that they missed an important point: only file extension with one period was taken into consider like *.png *.mp3, but how do I deal with these filename with two period like .tar.gz.

The basic code is:

filename = '/home/lancaster/Downloads/a.ppt' extention = filename.split('/')[-1] 

But obviously, this code do not work with the file like a.tar.gz. How to deal with it? Thanks.

like image 435
Page David Avatar asked Jun 18 '16 11:06

Page David


1 Answers

Python 3.4

You can now use Path from pathlib. It has many features, one of them is suffix:

>>> from pathlib import Path >>> Path('my/library/setup.py').suffix '.py' >>> Path('my/library.tar.gz').suffix '.gz' >>> Path('my/library').suffix '' 

If you want to get more than one suffix, use suffixes:

>>> from pathlib import Path >>> Path('my/library.tar.gar').suffixes ['.tar', '.gar'] >>> Path('my/library.tar.gz').suffixes ['.tar', '.gz'] >>> Path('my/library').suffixes [] 
like image 64
Or Duan Avatar answered Sep 24 '22 02:09

Or Duan