Samah
Samah

Reputation: 61

How to delete specific line from file using python?

The code is:

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()

The goal of this code is to :

1- loop on the lines in the file

2- check if any line it in the range of current time

3- if yes: print this line in range time: 9:1 and delete this line from the same file.

4-data in the file is:

7:1_8:35_2016-04-14
8:1_9:35_2016-04-14
9:1_10:35_2016-04-14

5- output must be:

7:1_8:35_2016-04-14
8:1_9:35_2016-04-14

because the last line has the time in range of current time.it must delete and replace empty line.

My problem is this code will clean all file and i don't want that:

invaild code: fonlyOnce.write(" ")

Thanks

Upvotes: 0

Views: 538

Answers (3)

galaxyan
galaxyan

Reputation: 6111

what I did:
1. remove determining function out of loop.
2. if not fit your needs, replace data with empty list
3. open a new file to write processed data

    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)

Upvotes: 1

lochsh
lochsh

Reputation: 376

  • You do not want to edit a file you are reading. This is a bad idea!

  • Instead, you might want to consider reading each line of the file into a list, deleting unwanted items from the list, then writing over the file with this list.

    If your file is large, this might be slow, however.

    Also, at the end of your code you call fonlyOnce.close(), but you don't need to. The context manager (the with statement) automatically closes the file once you leave it.

Upvotes: 0

Jason Qiao Meng
Jason Qiao Meng

Reputation: 37

Brute-force solution - suitable for small size files

0- create a buffer of lines

1- loop on the lines in the file

1.1- check if any line it in the range of current time

1.2- if yes: print this line in range time: 9:1 if no: add the line into the buffer

2- close the file for read

3- add an empty line into the buffer

4- reopen the file for write

5- flush the buffer into the file, and save the file

Upvotes: 0

Related Questions