如何打印文件的特定部分?

时间:2014-05-04 13:32:44

标签: python file

输入文件:

%-----------------------------------------
Task:
- [ ] Learn chapter-1
- [ ] Learn chapter-1

%-----------------------------------------
Finished Task:
- [x] Learn chapter-1

%-----------------------------------------
Upcoming Task:
- [*] Learn chapter-1

预期输出文件:

%-----------------------------------------
Task:
- [ ] Learn chapter-1
- [ ] Learn chapter-1
%-----------------------------------------

代码示例

data_file = open("test.txt")
block = ""
found = False

for line in data_file:
    if found:
        block += line
        if line.strip() == "Finished Task:": break
    else:
        if line.strip() == "Task":
            found = True
            block = "Task"

data_file.close()

问题是我想只打印任务之间的文本,包括带有%----------------的行。任何建议都非常感谢。谢谢

1 个答案:

答案 0 :(得分:1)

您的代码只需很少的修改即可运行:

data_file = open("task.txt")
block = ""
found = False

for line in data_file:
    if found:
        if line.strip() == "Finished Task:": 
           break
        else:                # <--
           block += line     # <--  
    else:
        if line.strip() == "Task:":  # <-- 
            found = True
            block = line

data_file.close()

此代码为我提供输出

Task:
- [ ] Learn chapter-1
- [ ] Learn chapter-1

%-----------------------------------------

这是你想要的吗?但是,在我看来,在这种情况下,最佳解决方案是通过正则表达式提供的