How to extract the file name from a file path?

This article here worked out just fine for me

import os
inputFilepath = 'path/to/file/foobar.txt'
filename_w_ext = os.path.basename(inputFilepath)
filename, file_extension = os.path.splitext(filename_w_ext)
#filename = foobar
#file_extension = .txt

path, filename = os.path.split(path/to/file/foobar.txt)
# path = path/to/file
# filename = foobar.txt

Hope it helps someone searching for this answer


If all you want to do is truncate the file paths to just the filename, you can use os.path.basename:

for file in files:
    fname = os.path.basename(file)
    dict_[fname] = (pd.read_csv(file, header=0, dtype=str, encoding='cp1252')
                      .fillna(''))

Example:

os.path.basename('Desktop/test.txt')
# 'test.txt'

import os
pathname ='c:\\hello\\dickins\\myfile.py'
head, tail = os.path.split(pathname)
print head
print tail

Tags:

Python