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

วิธี Touch ไฟล์ทั้งหมดแบบ Recursive ด้วย Python

เพื่อ Touch ไฟล์ทั้งหมดแบบ Recursive คุณต้อง Walk Directory Tree ด้วย os.walk และ Touch ไฟล์ทั้งหมดในมันด้วย os.utime(path_to_file)

ตัวอย่าง

import os

# Recursively walk the tree
for root, dirs, files in os.walk(path):
    for file in files:
        # Set utime to current time
        os.utime(os.path.join(root, file))

ใน Python 3.4+ คุณสามารถใช้โมดูล pathlib เพื่อ Touch Files ได้โดยตรง

ตัวอย่าง

from pathlib import Path
import os

# Recursively walk the tree
for root, dirs, files in os.walk(path):
    for file in files:
        Path(os.path.join(root, file)).touch()