Skip to content

Instantly share code, notes, and snippets.

@c0x6a
Created August 1, 2014 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save c0x6a/c6ce196f06d10d9cdc6b to your computer and use it in GitHub Desktop.
Save c0x6a/c6ce196f06d10d9cdc6b to your computer and use it in GitHub Desktop.
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