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

Touch (cập nhật timestamp) tất cả file đệ quy trong Python

Dùng os.walk + os.utime() (hoặc Path.touch() Python 3.4+) để cập nhật access/modified time thành thời điểm hiện tại.

os.utime (mọi version)

import os

for root, dirs, files in os.walk('.'):
    for file in files:
        filepath = os.path.join(root, file)
        os.utime(filepath)  # set atime/mtime = now

pathlib.Path.touch() (Python 3.4+)

from pathlib import Path
import os

for root, dirs, files in os.walk('.'):
    for file in files:
        Path(os.path.join(root, file)).touch()

pathlib thuần túy (rglob)

for f in Path('.').rglob('*'):
    if f.is_file():
        f.touch()

Lưu ý

  • os.utime(path, (atime, mtime)) cho phép set thời gian tùy chỉnh.
  • ns=(atime_ns, mtime_ns) cho độ chính xác nanosecond (Python 3.3+).