Skip to content

Instantly share code, notes, and snippets.

Created August 1, 2014 16:22
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Get filename and extension from a /path/to/
# coding=utf-8
def file_name_ext(path_to_file, with_dots=True):
Returns file_name and file_extension from a given path; if the file
has dots in its name and `with_dots` is False, they will be removed.
/some/long/path/to/file.txt will return ('file', 'txt')
/some/long/path/to/file.with.dots.txt will return ('filewithdots', 'txt')
:param path_to_file: Path to file or just a file
:param with_dots: Whether to keep dots in filename or not
:return: tuple
if '/' in path_to_file:
''' /some/long/path/to/ '''
path_to_file = path_to_file[path_to_file.rfind('/') + 1:]
file_extension = path_to_file[path_to_file.rfind('.') + 1:]
if with_dots:
file_name = '.'.join(path_to_file.split('.')[:-1])
file_name = ''.join(path_to_file.split('.')[:-1])
return file_name, file_extension
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment