It is easy to use python pathlib package to get some basic file path information. In this tutorial, we will use some examples to show you this topic.
How to use python pathlib to get file path information?
In order to use python pathlib, we should import it as follows:
from pathlib import Path
Then we can use this package to get file information.
We will use a file in D:\xampp\MercuryMail\manual.pdf as an example.
We will create a path object.
file = r'D:\xampp\MercuryMail\manual.pdf' path = Path(file)
1.Get parent directory
parent = path.parent print(parent)
Result: D:\xampp\MercuryMail
2.Get file name
filename = path.name print(filename)
Result: manual.pdf
3.Get file suffix
filesuffix = path.suffix print(filesuffix)
Result: .pdf
Notice: The suffix is .pdf, not pdf.
4.Get file name without suffix
filename = path.stem print(filename)
Result: manual
5.Is file or directory
if path.is_file(): print("This is file") if path.is_dir(): print("This is directory")
Result: This is file
6.Is absolute path
if path.is_absolute(): print("It is absolute") else: print("It is not absolute")
Result: It is absolute
7.Get current directory
print(path.cwd())
Result: D:\workspace\Test-Code
8.Join path
p = path.joinpath('test') print(p)
Result: D:\xampp\MercuryMail\manual.pdf\test
9.Is exist
if path.exists(): print("This file is exist") else: print("This file is not exist")
Result: This file is exist
Reference