Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python OS Module คืออะไร และการใช้งานพื้นฐาน

บทนำ

โมดูล os ให้ฟังก์ชันสำหรับโต้ตอบกับระบบปฏิบัติการ: จัดการไฟล์/โฟลเดอร์, environment variables, process control

การเริ่มต้น

os มาพร้อม Python: import os

ฟังก์ชันหลักและตัวอย่าง

1. os.getcwd() - โฟลเดอร์ทำงานปัจจุบัน

import os
os.getcwd()

2. os.mkdir(path) - สร้างโฟลเดอร์

import os
os.mkdir("D:\\Tutorialspoint")  # สร้างใน D drive
# ถ้าไม่ระบุ path จะสร้างใน current working directory

3. os.rmdir(path) - ลบโฟลเดอร์ว่าง

import os
os.rmdir("D:\\Tutorialspoint")

หมายเหตุ: ไม่สามารถลบ current working directory ได้

4. os.rename(src, dst) - เปลี่ยนชื่อโฟลเดอร์/ไฟล์

import os
os.mkdir("D:\\Tutorialspoint")
os.rename("D:\\Tutorialspoint", "D:\\Tutorialspoint2")

5. การจัดการไฟล์พื้นฐาน

สร้างไฟล์: file = os.popen("Hello.txt", 'w')
เขียนเนื้อหา: file.write("Hello there!")

โปรแกรมตัวอย่างครบถ้วน

import os
os.getcwd()
os.mkdir("D:\\Tutorialspoint")
os.rmdir("D:\\Tutorialspoint")
os.mkdir("D:\\Tutorialspoint")
os.rename("D:\\Tutorialspoint", "D:\\Tutorialspoint2")
file = os.popen("Hello.txt", 'w')
file.write("Hello there! This is a tutorialspoint article")

สรุป

os module ครอบคลุมการจัดการ filesystem พื้นฐาน สำหรับงานขั้นสูง (walk, stat, symlink, permission) ดูเอกสาร: https://docs.python.org/3/library/os.html