When operating files in python, there some basic operations we shoud notice, for example, how to get directory, file name and file extension. In this tutorial, we will introduce how to get these file information.
Import library
import os
Create an absolute path
file = r'E:\workspace-python\examples\test.py'
Get directory name
dirname = os.path.dirname(file) print(dirname)
The output is:
E:\workspace-python\examples
Get file name
basename = os.path.basename(file) print(basename)
The output is:
test.py
Get file name without file extension
info = os.path.splitext(basename) filename = info[0] print(filename)
The file name is:
test
Get file extension
extend = info[1] print(extend)
The file extension is:
.py
Here we can build a function to get these basic file information.
def getFilePathInfo(absolute): dirname = os.path.dirname(absolute) basename = os.path.basename(absolute) info = os.path.splitext(basename) filename = info[0] extend = info[1] return dirname, filename, extend
How to use?
info = getFilePathInfo(file) print(info)
The file information is:
('E:\\workspace-python\\examples', 'test', '.py')