Content
- Check existence
- Check type
- File information
- Creating and writing a file
- Creating a folder
- Creating a link to a file
Assume:
from pathlib import Path
file_path = Path("example.txt")
folder_path = Path("my_folder")
link_path = Path("link_to_example")
Check existence
print("File exists?", file_path.exists())
print("Folder exists?", folder_path.exists())
print("Link exists?", link_path.exists())
File exists? True
Folder exists? True
Link exists? True
Check type
print("Is file?", file_path.is_file())
print("Is directory?", file_path.is_dir())
print("Folder is directory?", folder_path.is_dir())
print("Folder is file?", folder_path.is_file())
print("Link is symlink?", link_path.is_symlink())
Is file? True
Is directory? False
Folder is directory? True
Folder is file? False
Link is symlink? True
File information
info = file_path.stat()
print("File size (bytes):", info.st_size)
print("Last modification:", info.st_mtime)
print("Last access:", info.st_atime)
File size (bytes): 14
Last modification: 1759656090.213048
Last access: 1759656090.213048
Note: Timestamps in epoch format
Creating and writing a file
if not file_path.exists():
file_path.write_text("Test content\n")

Creating a folder
if not folder_path.exists():
folder_path.mkdir()

Creating a link to a file
if not link_path.exists():
try:
link_path.symlink_to(file_path) # may not work on Windows without admin permissions
except Exception as e:
print("Could not create symlink:", e)

Python
05 Oct. 2025
|
Last Updated: 22 Nov. 2025
|
jaimedcsilva Related