โมดูล os.path เป็นโมดูลที่ใช้กันอย่างแพร่หลายและมีประโยชน์มากเมื่อประมวลผลไฟล์จากตำแหน่งต่างๆ ในระบบ ใช้เพื่อวัตถุประสงค์ต่างๆ เช่น การรวม จัดรูปแบบ และดึงชื่อ path ใน Python ฟังก์ชันทั้งหมดนี้รับพารามิเตอร์เป็น bytes เท่านั้นหรือ string objects เท่านั้น ผลลัพธ์เฉพาะเจาะจงไปกับ OS ที่รัน
os.path.basename
ฟังก์ชันนี้ให้ส่วนสุดท้ายของ path ซึ่งอาจเป็นโฟลเดอร์หรือชื่อไฟล์ โปรดสังเกตความแตกต่างในการระบุ path ใน Windows และ Linux ในแง่ของ backslash และ forward slash
ตัวอย่าง
import os
# In windows
fldr = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites")
print(fldr)
file = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html")
print(file)
# In nix*
fldr = os.path.basename("/Documents/MyWebSites")
print(fldr)
file = os.path.basename("/Documents/MyWebSites/music.txt")
print(file)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
My Web Sites intro.html MyWebSites music.txt
os.path.dirname
ฟังก์ชันนี้ให้ชื่อไดเรกทอรีที่โฟลเดอร์หรือไฟล์ตั้งอยู่
ตัวอย่าง
import os
# In windows
DIR = os.path.dirname("C:\\Users\\xyz\\Documents\\My Web Sites")
print(DIR)
# In nix*
DIR = os.path.dirname("/Documents/MyWebSites")
print(DIR)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
C:\Users\xyz\Documents /Documents
os.path.isfile
บางครั้งเราอาจต้องตรวจสอบว่า path ที่ให้มาทั้งหมด แทนโฟลเดอร์หรือไฟล์ ถ้าไฟล์ไม่มีอยู่จริง จะให้ False เป็นผลลัพธ์ ถ้าไฟล์มีอยู่ ผลลัพธ์คือ True
ตัวอย่าง
print(IS_FILE)
IS_FILE = os.path.isfile("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html")
print(IS_FILE)
# In nix*
IS_FILE = os.path.isfile("/Documents/MyWebSites")
print(IS_FILE)
IS_FILE = os.path.isfile("/Documents/MyWebSites/music.txt")
print(IS_FILE)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
False True False True
os.path.normpath
นี่คือฟังก์ชันที่น่าสนใจซึ่งจะ normalize path ที่กำหนดโดยกำจัด slash เพิ่มเติม หรือเปลี่ยน backslash เป็น forward slash ขึ้นอยู่กับ OS ที่รัน ตามที่คุณเห็นผลลัพธ์ด้านล่างแตกต่างกันไปตาม OS ที่คุณรันโปรแกรม
ตัวอย่าง
import os
# Windows path
NORM_PATH = os.path.normpath("C:/Users/Pradeep/Documents/My Web Sites")
print(NORM_PATH)
# Unix Path
NORM_PATH = os.path.normpath("/home/ubuuser//Documents/")
print(NORM_PATH)
การรันโค้ดด้านบนให้ผลลัพธ์ดังนี้:
ผลลัพธ์
# Running in Windows C:\Users\Pradeep\Documents\My Web Sites \home\ubuuser\Documents # Running in Linux C:/Users/Pradeep/Documents/My Web Sites /home/ubuuser/Documents