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

Tạo file rỗng trong Python (touch)

Nhiều cách tạo file rỗng (hoặc cập nhật timestamp nếu đã tồn tại — hành vi touch Unix).

1. open() mode 'a' + close() (cơ bản)

open('my_file.txt', 'a').close()

2. pathlib.Path.touch() (Python 3.4+, khuyến nghị)

from pathlib import Path
Path('my_file.txt').touch()
# Tạo file nếu chưa có, cập nhật mtime/atime nếu đã có
Path('my_file.txt').touch(exist_ok=True)  # mặc định
Path('my_file.txt').touch(mode=0o644)     # set permission

3. os.mknod() (Unix, tạo filesystem node)

import os
os.mknod("my_file.txt")  # chỉ Unix, cần quyền

4. Mở write mode (truncate nếu tồn tại)

open('my_file.txt', 'w').close()  # cắt rỗng file nếu đã có

Khuyến nghị: Path.touch() — rõ ràng, cross-platform, hỗ trợ exist_ok, mode.