我正在编写一个程序,删除带有YYYY-MM-DD日期的目录作为名称。我很难写一个方法,它创建了一个要删除的文件夹的路径名列表。将它们添加到此列表的条件是文件夹名称中的日期年龄。
我无法让程序识别这些较旧的日期。
import os
import sys
import datetime
import config #this is by me
global archivePath # config value: "/archive/"
global archiveForDays # config value: 14
archivePath = config.archivePath
archiveForDays = config.archiveForDays
def getDestruDirList():
# This method creates a list of files for deletion.
archiveList = os.listdir(archivePath) #get list of archive directorires
deletionList = [] #create list for deletion
for dateStr in archiveList:
skip = False
if (not dateStr == "current"):
dateVar = datetime.datetime.strptime(dateStr, "%Y-%m-%d")
if dateVar.date < datetime.datetime.now() - datetime.timedelta(days=archiveForDays):
deletionList.append(archivePath + dateStr) #add full pathname to deletion list
print("Revision " + dateVar.strftime("%d-%m-%Y") + " to be deleted.")
return deletionList
测试这个不起作用,我对日期不是很熟悉,之前从未见过这个错误。对该方法的测试失败如下......
Python 3.4.3 (default, Sep 9 2016, 06:04:18)
[GCC 4.9.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cleaner
>>> cleaner.getDestruDirList()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/archive-scripts/cleaner.py", line 22, in getDestruDirList
if dateVar.date < datetime.datetime.now() - datetime.timedelta(days=archiveForDays):
TypeError: unorderable types: builtin_function_or_method() < datetime.datetime()
编辑:我对TypeError问题更加确定,但我不知道该怎么办,而且卡住了。
答案 0 :(得分:0)
问题是导致使用错误类型的一些语法错误。在研究解决方案的某些时候,我可能犯了查看Python2示例的错误。这是一个经过单元测试的完成方法,它生成一个以超过特定天数的日期命名的目录列表。
def getDestruDirList():
# This method creates a list of files for deletion.
archiveList = os.listdir(archivePath) #get list of archive directorires
deletionList = [] #create list for deletion
for dateStr in archiveList:
skip = False
if (not dateStr == "current"):
dateVar = datetime.datetime.strptime(dateStr, "%Y-%m-%d")
if dateVar.date() < datetime.datetime.now().date() - datetime.timedelta(days=archiveForDays):
deletionList.append(archivePath + dateStr) #add full pathname to deletion list
print("Revision " + dateVar.strftime("%d-%m-%Y") + " to be deleted.")
return deletionList