Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạo tên file tạm duy nhất bằng Python?


Dùng module tempfile tạo file tạm duy nhất an toàn nhất. Không race condition. File chỉ readable/writable bởi user tạo. Người dùng mkstemp() tự xóa file tạm khi xong. Tạo file tạm mới:

import tempfile
_, temp_file_path = tempfile.mkstemp()
print("File path: " + temp_file_path)

Lưu ý: phải tự xóa file này sau khi xong.