Giới thiệu
Module os cung cấp các hàm tương tác với hệ điều hành: tạo/xóa/thay tên thư mục, xử lý file cơ bản.
Bắt đầu
Module os có sẵn trong Python, không cần cài pip.
import os
Lấy thư mục làm việc hiện tại
import os os.getcwd()
Lưu ý: Directory = thư mục (folder).
Tạo thư mục
import os
os.mkdir("D:\\Tutorialspoint")
Tạo folder Tutorialspoint ở ổ D. Nếu không chỉ định đường dẫn, tạo ở thư mục hiện tại.
Xóa thư mục
import os
os.rmdir("D:\\Tutorialspoint")
Lưu ý: Không thể xóa thư mục đang chạy script (current working directory).
Đổi tên thư mục
import os
os.mkdir("D:\\Tutorialspoint")
os.rename("D:\\Tutorialspoint", "D:\\Tutorialspoint2")
Thao tác file cơ bản
Tạo file
file = os.popen("Hello.txt", 'w')
Ghi nội dung
file = os.popen("Hello.txt", 'w')
file.write("Hello there! This is a tutorialspoint article")
Lưu ý: os.rename cũng đổi tên file được, nhớ giữ đúng phần mở rộng.
Ví dụ hoàn chỉnh
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")
Kết luận
Đã nắm cơ bản os module. Xem thêm tại tài liệu chính thức.