โจทย์: หา Directory Path ที่ยาวที่สุดและซ้ำกัน (Common prefix) จากลิสต์ของ File Paths
Input/Output
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django'] Output: home/tutorialspoint
วิธีแก้: ใช้ os.path Module
os.path.commonprefix(paths)หา Common prefix ของสตริงทั้งหมดos.path.dirname(common_prefix)ดึงเฉพาะ Directory path (ตัดไฟล์/โฟลเดอร์สุดท้ายออก)
ตัวอย่างโค้ด
import os paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django'] common_prefix = os.path.commonprefix(paths) longest_common_directory = os.path.dirname(common_prefix) print(longest_common_directory)
ผลลัพธ์
home/tutorialspoint
โมดูล os.path อื่นๆ ที่น่าสนใจ:
os.path.join()- รวม path อย่างปลอดภัยos.path.basename()- ดึงชื่อไฟล์/โฟลเดอร์สุดท้ายos.path.split()- แยก (head, tail)os.path.relpath()- หา Relative path
ข้อควรระวัง: commonprefix ทำงานแบบ Character-by-character ไม่ใช่ Path-component อาจให้ผลลัพธ์ผิดหากชื่อโฟลเดอร์มี prefix เหมือนกัน (เช่น /home/user1 และ /home/user2 จะได้ /home/user) ควรใช้ os.path.commonpath (Python 3.5+) แทน