【发布时间】:2016-04-14 16:56:55
【问题描述】:
代码为:
from datetime import datetime,time
from csv import reader
with open('onlyOnce.txt', 'r+') as fonlyOnce:
for f_time, sec_time, dte in filter(None, reader(fonlyOnce, delimiter="_")):
check_stime=f_time.split(":")
Stask_hour=check_stime[0]
Stask_minutes=check_stime[1]
check_stime = datetime.strptime(f_time,"%H:%m").time()
check_etime=sec_time.split(":")
Etask_hour=check_etime[0]
Etask_minutes=check_etime[1]
#check every minute if current information = desired information
now = datetime.now()
now_time = now.time()
date_now = now.date()
if (date_now.strftime("%Y-%m-%d") == dte and time(int(Stask_hour),int(Stask_minutes)) <= now_time <= time(int(Etask_hour),int(Etask_minutes))):
print("this line in range time: "+ f_time)
#delete this line
fonlyOnce.write(" ")
else:
print("Padraic Cunningham")
fonlyOnce.close()
这段代码的目标是:
1-循环文件中的行
2-检查当前时间范围内是否有行
3- 如果是:打印this line in range time: 9:1 并从同一文件中删除这一行。
文件中的4-数据为:
7:1_8:35_2016-04-14
8:1_9:35_2016-04-14
9:1_10:35_2016-04-14
5- 输出必须是:
7:1_8:35_2016-04-14
8:1_9:35_2016-04-14
因为最后一行的时间在当前时间范围内,所以必须删除替换空行。
我的问题是这段代码会清理所有文件,我不希望这样:
无效代码:fonlyOnce.write(" ")
谢谢
【问题讨论】:
-
你有缩进问题,fonlyOnce开头少了一个空格....已经编辑过了。
-
我认为您尝试就地执行此操作过于复杂。您是否尝试过将要保留的行写到临时文件中,然后在最后用临时文件替换原始文件?
标签: python