Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get filename and extension from a /path/to/foofile.bar
# 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.
Example:
/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/foofile.bar '''
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])
else:
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