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

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

这段代码的目的是:检查每行的当前时间,当当前行在“第一行”范围内时//do somthing ,就像 make Schedule 或 Alarm 一样。

错误是:

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

但我想问一个愚蠢的问题:/ 当我检查这个逻辑时,不会打印"is"!但日期等于 2016-04-14 那么为什么不正确? O.o我很困惑

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

感谢每一位帮助过我的人:Padric Cunningham 和其他人

最佳答案

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

关于python - 如何使用 python 从文件中分割每一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36626130/

相关文章:

c - feof(in) != EOF 不会使 while 循环在文件末尾停止?

python - 调用属性 getter、setter、deleter - Python

Python Tkinter 布局管理

python - 是否可以创建 mediapipe body 姿势地标和连接的动画 3D 散点图?

ios - 我可以在 iOS 中为文件设置任意属性吗?

java - 适用于整个文本文件的 OpenNLP 句子检测 API

python - 如何修补基类方法?

Python寻找第N个素数

c - 有没有办法在读取文本文件后删除第一个字符?

jquery - 如何获取jquery文件上传插件的文件列表?