【问题标题】:How can i delete files in a folder and subfolders using python in windows machine?如何在 Windows 机器中使用 python 删除文件夹和子文件夹中的文件?
【发布时间】:2018-12-23 07:41:17
【问题描述】:

我想删除除隐藏文件外的所有超过 1 天的文件

我已经尝试了下面的代码,但它似乎也试图删除隐藏文件,我该如何修改它以便删除所有文件而不是隐藏文件?

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

我可能不明白。更简单的代码将不胜感激。

【问题讨论】:

  • 我投票决定将此问题作为题外话结束,因为 SO 不是代码编写服务
  • 我没找到你?怎么跑题了? @DeepSpace
  • How to Ask......
  • 首先,展示你的尝试
  • 不要问“我想做X,请给我codez”;问“我想做X。我试过Y。我的代码正确地做了这部分,但是这部分不起作用,因为Z。我研究了这个主题并找到了这些相关资源(A,B),但我仍然想不出解决办法。”换句话说,向我们表明您已尝试解决问题。这个问题由 4 个小问题组成:列出文件夹中的所有文件,检查文件是否超过一天,检查它是否是隐藏文件,然后删除它。没有我们的帮助,您肯定可以解决其中的一两个问题吗?

标签: python windows python-2.7


【解决方案1】:

此代码适用于 windows 文件系统,我没有检查 unlink 部分(这是正确的,我的假设):代码 cmets 中的代码解释。顺便说一句 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

【讨论】:

  • 我收到错误:没有模块文件 win32file 。我正在使用 python 2.7
  • stackoverflow.com/questions/23864234/… ,对于python 2.7,你可以参考这个链接。
  • 我安装了适用于 python 3 的 anaconda,无需任何安装即可工作。你可以,或者参考我给的链接。
  • 如果您使用它,请点赞并标记答案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多