繁体   English   中英

删除 python 中 90 天之前的文件行

[英]Delete in lines in file with that older then 90 days in python

我有一个包含日期的文件,我想删除所有超过 90 天的日期。 例子:

2020-02-26
2009-03-21
2021-04-12
2021-01-21

我想不出办法做到这一点。

到目前为止,我能做的是仅从文件中提取日期并将其打印为列表:

file = open('dates_file', 'r')
Lines = file.readlines()

count = 0
# Strips the newline character
for line in Lines:
    count += 1
    #print(line.strip())
    index = 10
    if len(line) > index:
        line = line[0: index :]
        print(line.strip())

编辑:

我已经编辑了脚本并且能够从 90 天前提取日期以将其与文件中的日期进行比较,并且我能够获得需要删除的所有日期的 output。

这是到目前为止的脚本:

past = datetime.now().date() - timedelta(days=90)
present = datetime.now()
index = 10

file = open('dates_file', 'r')
Lines = file.readlines()


count = 0
# Strips the newline character
for line in Lines:
    count += 1
    if len(line) > index:
        line = line[0: index :]
    if line.strip() < str(past):
        print(line.strip())

文件中的日期是 ISO 格式,其优点是可以按词法比较该样式的日期。 因此你可以这样做:

from datetime import datetime, timedelta, date
# calculate and format a date that is 90 days prior to the current date
prev = date.strftime(datetime.today() - timedelta(days=90), '%Y-%m-%d')

with open('dates_file', 'r+') as dates:
    # build a list of dates that are greater than *prev*
    d = [s for s in dates if s.strip() > prev]
    dates.seek(0) # seek to start of file
    dates.write(''.join(d)) # write the list
    dates.truncate() # truncate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM