python 删除 x 天内无人访问的文件

python delete files no one accessed in x days

我想编写一个 python 脚本来删除在 >= x 天内未访问的文件。 我知道我可以检查文件的创建时间和修改时间,但我能以某种方式检查上次访问的时间吗?

谢谢, 李

您可以使用 'stat' 检查上次打开文件的时间, 使用 'time' 检查已经过去了多少时间, 并使用 'os':

删除它
import os
import stat
import time

fileStats = os.stat(filePath)
last_access = fileStats[stat.ST_ATIME] # in seconds
now = time.time() # in seconds
days = (now - last_access)  / (60 * 60 * 24) 
# The seconds that have elapsed since the file was last opened are divided by the number of seconds per day 
# this give the number of days that have past since the file last open

if x <= days:
  # we delete the file
    os.remove(filePath)