Samah
Samah

Reputation: 61

How to split each line from file using python?

I try to split contents from file, this file has many lines and we don't know how much lines as example i have these data in the file:

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

using paython i want to loop at each line and split each line like that:

for line in iter(file):
    task =line.split("_")
    first_time=task[0] #8:1
    second_time=task[1] #9:35
    date=task[2] #2016-04-15

But this will give me: task[0] is first line task[1] is second line and so on .... how i can read only one line at a time and split its content to do do something and the same thing with the other lines.

Update my question: full code :

with open('onlyOnce.txt', 'r') as fp:
    for f_time, sec_time, dte in filter(None, reader(fp, delimiter="_")):

        check_stime=f_time.split(":")
        Stask_hour=check_stime[0]
        Stask_minutes=check_stime[1]

        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 (time(Stask_hour,Stask_minutes) <= now_time <= time(Etask_hour,Etask_minutes) and date_now == dte):
            print("this line in range time: "+ f_time)
        else:
            print("")
fp.close()

My aim from this code is: to check current time with each line, and when the current line in the range of the "first line" //do somthing , it is like make schedule or alarm .

Error is:

Traceback (most recent call last):
  File "<encoding error>", line 148, in <module>
TypeError: 'module' object is not callable

OKay, final Update is:

from datetime import datetime,time
from csv import reader

with open('onlyOnce.txt', 'r') as fp:
    for f_time, sec_time, dte in filter(None, reader(fp, delimiter="_")):

        check_stime=f_time.split(":")
        Stask_hour=check_stime[0]
        Stask_minutes=check_stime[1]

        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 time(int(Stask_hour),int(Stask_minutes)) <= now_time <= time(int(Etask_hour),int(Etask_minutes) and dte == date_now):
            print("this line in range time: "+ f_time)
        else:
            print("")
fp.close()

But i want to ask a Stupid question :/ When i check this logic, will not print "yes" !! but date is equal 2016-04-14 so why not correct ?? O.o i'm confused

if('2016-04-14' == datetime.now().date() ):
    print("yes")

Thanks for every one helped me : Padraic Cunningham and others

Upvotes: 1

Views: 178

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

Use a csv reader passing a file object and use _ as the delimiter:

from csv import reader

with open("infile') as f:
   # loop over reader getting a row at a time
   for f_time, sec_time, dte in reader(f, delimiter="_"):   
       print(f_time, sec_time, dte )

Which will give you something output like:

In [2]: from csv import reader
In [3]: from StringIO import StringIO

In [4]: for f,s,d in reader(StringIO(s), delimiter="_"):
   ...:         print(f,s,d)    
   ...:     
('7:1', '8:35', '2016-04-14')
('8:1', '9:35', '2016-04-15')
('9:1', '10:35', '2016-04-16')

Since you have empty lines we need to filter those out:

with open("infile') as f:
   for f_time, sec_time, dte in filter(None, reader(f, delimiter="_")):   
       print(f_time, sec_time, dte )

So now empty rows will be removed:

In [5]: s = """7:1_8:35_2016-04-14
   ...: 8:1_9:35_2016-04-15
   ...: 
   ...: 9:1_10:35_2016-04-16"""
In [6]: from csv import reader    
In [7]: from StringIO import StringIO    
In [8]: for f,s,d in filter(None, reader(StringIO(s), delimiter="_")):
   ...:         print(f,s,d)
   ...:     
('7:1', '8:35', '2016-04-14')
('8:1', '9:35', '2016-04-15')
('9:1', '10:35', '2016-04-16')

If you want to compare the current date and the hour and minute against the current time:

from datetime import datetime
from csv import reader

with open('onlyOnce.txt', 'r') as fp:
    for f_time, sec_time, dte in filter(None, reader(fp, delimiter="_")):
        check_stime = f_time.split(":")
        stask_hour= int(check_stime[0])
        stask_minutes = int(check_stime[1])
        check_etime = sec_time.split(":")
        etask_hour = int(check_etime[0])
        etask_minutes = int(check_etime[1])

        # check every minute if current information = desired information
        now = datetime.now()
        hour_min_sec = now.hour, now.minute, now.second

        if now.strftime("%Y-%d-%m") == dte and (stask_hour, stask_minutes, 0) <= hour_min_sec <= (etask_hour, etask_minutes, 0):
            print("this line in range time: " + f_time)
        else:
            print("")

Or a simpler way may be to just parse the times:

from datetime import datetime
from csv import reader

with open('onlyOnce.txt', 'r') as fp:
    for f_time, sec_time, dte in filter(None, reader(fp, delimiter="_")):
        check_stime = datetime.strptime(f_time,"%H:%m").time()
        check_etime = datetime.strptime(f_time,"%H:%m").time()
        # check every minute if current information = desired information
        now = datetime.now()

        if now.strftime("%Y-%d-%m") == dte and check_etime  <= now.time() <= check_etime:
            print("this line in range time: " + f_time)
        else:
            print("")

Upvotes: 1

egor_hm
egor_hm

Reputation: 280

That is the most efficient way to read file by loading one line by line into memory.

def parse_line(line):
    splitted = line.split('_')
    first = splitted[0]
    second = splitted[1]
    date = splitted[2]


with open('test.txt', 'r') as fp:
    for line in fp:
        parse_line(line)

Upvotes: 1

Related Questions