We use pathlib and forward slashes so that the Path() function can be used to automatically convert backslash to forward slash on Linux systems.
Does file exist?
from pathlib import Path
if not Path('C:/MyDirectoryname/MyFileName.txt').exists():
print("Does not exist")
Getting file name elements
from pathlib import Path
my_path = Path("some_folder/some_sub_folder/my_filename.txt")
print(my_path.name) #Prints "my_filename.txt"
print(my_path.suffix) #Prints "txt
print(my_path.stem) #Prints "my_filename"
Delete file
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.