Created
August 1, 2014 16:22
-
-
Save c0x6a/c6ce196f06d10d9cdc6b to your computer and use it in GitHub Desktop.
Get filename and extension from a /path/to/foofile.bar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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