r/pythonhelp • • May 15 '21

How to selectively print lines of text from an external file if they meet certain factors

Sorry for the vague titles, I wasn't sure how to word the question

My goal is to print lines if they are set as incomplete so if:

a = incomplete

b = complete

c = complete

d = incomplete

etc.

then the file would be read and print 'a' and 'd' on seperate lines

Thanks for any help, Im kinda a noob at python

4 Upvotes

3 comments sorted by

2

u/socal_nerdtastic May 15 '21
with open(filename) as f:
    for line in f:
        if "incomplete" in line:
            print(line, end='')

1

u/xCustomWorld May 16 '21 edited May 16 '21

If your file follows just a consistent, simple format such as:

a=incomplete
b=complete
abc=incomplete

then you can do it more accurately, although this might be too advanced for beginners:

def obtain_incomplete():
    not_completed = list() # create a list for completed tasks

    for line in open("path/to/file"):
        pair = line.strip().split("=", maxsplit=1) # strips line of whitespaces and newlines, create list out of it

        if pair[1] == "incomplete": # if something after = is "incomplete"
            not_completed.append(pair)

    return not_completed

Example output:

not_completed = obtain_incomplete()
not_completed == [['a', 'incomplete'], ['abc', 'incomplete']]

This will cause issues with whitespaces, eg:

a = b

The advantage is that you can access task & state easily:

pair[0] = task, before =
pair[1] = completeness state, after =

You can also yield completed tasks only by using generator to make it more performant with large files, but that's a topic for next time

So, to print only incomplete task names:

for task in obtain_incomplete():
    print(task[0])

If you are looking for a quick solution, check out u/socal_nerdtastic's answer

My alternative, easiest solution that works with large files:

for line in open("path"):
    if line.endswith("incomplete"):
        print(line)

1

u/FpggyJohnson18 May 17 '21

And to go a step farther (on mobile, sorry for formatting)

[print(line) for line in open("path") if line.endswith("incomplete")]