onur cevik
onur cevik

Reputation: 107

Printing TODO: comments from a text file in Python

In my Project I want to extract the to do list from a text file. Here is my progress so far.

This is the content of todolist.txt text file

#TODO:example4
def printName():
    name=input("Enter your name: ")
    print("Hello " + name)
 TODO:example3
def printNumbers():
    for i in range (0,10):#TODO:example2
        print(i)


printName()
printNumbers()
#TODO: example1

and here is my Python code for extracting lines with TODO:

file=open("todolist.txt","r")

word="TODO:"

for line in file:
    if word in line:
        print(line)

And when I run this program the result is:

#TODO:example4

 TODO:example3

    for i in range (0,10):#TODO:example2

#TODO: example1


Process finished with exit code 0

So my problem is here I want to extract and print TODO lines only but as you can see from above, for #TODO:example2 my program printed the previous code on that spesific line too.

What I want to do is basicly just printing TODO comments.

Upvotes: 1

Views: 1677

Answers (2)

DeepSpace
DeepSpace

Reputation: 81654

You can use a regex:

import re

with open("todolist.txt") as f:
    file_content = f.read()

print(re.findall(r'^\s*#TODO:.+$', file_content, re.MULTILINE))

# ['#TODO:example4', '#TODO: example1']

'^\s*#TODO:.+$' will match every line that:

  • starts with any number of spaces (0 or more)
  • contains #TODO followed by anything (1 or more)
  • contains nothing else

Upvotes: 0

Lafexlos
Lafexlos

Reputation: 7735

You can split the line by 'TODO' then get the last item.

word="TODO:"
with open("todolist.txt") as file:    
    for line in file:
        if word in line:
            print("#TODO:" + line.split(word)[-1])

Upvotes: 2

Related Questions