Member-only story
Python: Habits that give away inexperience — Part 2
Python offers a wide range of powerful built-in functions that help save time, simplify code, and enhance performance.
Many Python functions are often underutilized, especially by beginners, who later realize that Python already offers efficient solutions. Additionally, there are various tricks and alternative coding approaches that can make programs cleaner and more efficient.
Here are some advanced coding mistakes or gaps in awareness of Python’s built-in functions that I believe one should address to unlock Python’s full potential —
1. Not using built in pathlib
Instead of doing string operation for manipulating the paths, use pathlib
module. As the former method is more error prone, inconsistent across OS.pathlib
provides a cross-platform, object-oriented approach to file paths. pathlib
makes file operations safer and more readable.
import os
file_path = "C:\\Users\\User\\Documents\\file.txt"
dir_name = os.path.dirname(file_path)
file_name = os.path.basename(file_path)
After: Using pathlib
from pathlib import Path
file_path = Path("C:/Users/User/Documents/file.txt")…