如何使用python从文件中删除特定行?

时间:2016-04-14 16:56:55

标签: python

代码为:

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

因为最后一行的时间在当前时间范围内。必须删除并替换空行。

我的问题是这段代码会清理所有文件而我不想要:

invaild代码:fonlyOnce.write(" ")

由于

3 个答案:

答案 0 :(得分:1)

我做了什么:
1.删​​除循环中的确定功能。
2.如果不符合您的需求,请将数据替换为空列表
3.打开一个新文件来编写处理过的数据

    def IsFit( f_time, sec_time, dte ):
        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))):
            return False
        else:
            return True

    with open('onlyOnce.txt', 'r+') as fonlyOnce:
        res = [  line if IsFit(*line ) else [] for line in csv.reader(fonlyOnce, delimiter="_") if line ]

    with open(NewFile,'wb') as f:
        wirter = csv.wither(f)
        wirter.writerows(res)

答案 1 :(得分:0)

蛮力解决方案 - 适用于小尺寸文件

0-创建行缓冲区

1-循环文件中的行

1.1-检查当前时间范围内是否有任何行

1.2-如果是:在范围时间内打印此行:9:1        如果否:将该行添加到缓冲区

2-关闭文件以供阅读

3-在缓冲区中添加一个空行

4-重新打开文件进行写入

5-将缓冲区刷入文件,然后保存文件

答案 2 :(得分:0)

  • 您不想编辑正在阅读的文件。这是一个坏主意!

  • 相反,您可能需要考虑阅读文件的每一行 进入列表,从列表中删除不需要的项目,然后写入 带有此列表的文件。

    但是,如果您的文件很大,这可能会很慢。

    此外,在代码的最后,您调用fonlyOnce.close(),但您不需要。上下文管理器(with语句)会在您离开文件后自动关闭该文件。

相关问题