如何使用python从文件中分割每一行?

时间:2016-04-14 14:25:55

标签: python file

我尝试从文件中分割内容,这个文件有很多行,我们不知道有多少行 例如,我在文件中有这些数据:

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

使用paython我希望在每一行循环并将每一行分开:

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

但这会给我: 任务[0]是第一行 任务[1]是第二行等等......我怎么一次只读一行并将其内容拆分成与其他行做同样的事情。

更新我的问题:完整代码:

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

我的目标是:检查每一行的当前时间,当“第一行”范围内的当前行//做某事时,就像制定计划或报警。

错误是:

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

好的,最后的更新是:

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

但我想问一个愚蠢的问题:/ 当我检查这个逻辑时,不会打印“是”!!但是日期相等2016-04-14所以为什么不正确?哦,我很困惑

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

感谢每一个人帮助我:Padraic Cunningham和其他人

2 个答案:

答案 0 :(得分:1)

使用csv reader传递file object并使用_作为分隔符:

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 )

这将为您提供如下输出:

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

由于你有空行我们需要过滤掉那些:

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

现在空行将被删除:

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

如果您想将当前日期和小时和分钟与当前时间进行比较:

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

或者更简单的方法就是解析时间:

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

答案 1 :(得分:1)

这是通过逐行加载到内存中来读取文件的最有效方法。

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)