我想删除除隐藏文件之外的所有超过一天的文件
我已经尝试了下面的代码,但它似乎也试图删除隐藏文件,我如何修改它,使其删除所有文件,但不删除隐藏文件?
import os
import time
current_time = time.time()
for f in os.listdir():
creation_time = os.path.getctime(f)
if (current_time - creation_time) // (24 * 3600) >= 1:
os.unlink(f)
print('{} removed'.format(f))
如果是linux,我可以这么做,
if not f.startswith('.'):
我已经浏览了以下链接:https://bitbucket.org/aafshar/pida-main/src/tip/pida/services/filemanager/filemanager.py
我可能不理解它。一个更简单的代码将不胜感激。
发布于 2018-07-16 02:08:14
这段代码是针对windows文件系统的,我没有检查取消链接部分(这是正确的,我的假设):代码注释中的代码解释。btw 24 * 3600 == 86400 ( 24小时,单位为秒)
import os
import time
import win32file
import win32con
from datetime import datetime
#convert float to datetime obj, current time
current_time = datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),'%Y-%m-%d %H:%M:%S')
for f in os.listdir():
#file's time to datetime object
creation_time = datetime.strptime(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(f))),'%Y-%m-%d %H:%M:%S')
#subtract both the time -->timedelta object
z= current_time - creation_time
#get windows attribute for the file
file_flag = win32file.GetFileAttributesW(f)
#check the attribute value for files in windows, for hidden files the attribute should be '2'
is_hidden = file_flag & win32con.FILE_ATTRIBUTE_HIDDEN
if ((z.seconds >= 86400) and (is_hidden != 2)):
os.unlink(f)
print('{} removed'.format(f))
windows文件系统代码参考:link
https://stackoverflow.com/questions/51350288
复制相似问题