I'm trying to read a text file where I want to remove the newlines, then split it into smaller strings and then compare the years against 2000

Viewed 27

This is my code:

with open("Land_and_Ocean_summary.txt", "r") as f:
list_of_lines = f.readlines()

for line in list_of_lines:
    line.strip()
    line.split()
    year = int(year)
    if line.isdigit() >= 2000:
        print(line)

And my text file looks like this: Data set

1 Answers

Functions like strip() and split() don't change the object they're called from (in this case line), they just return a new value that you need to store in another variable.

isdigit() also only returns True or False, so you still have to convert the string to an integer for the comparison.

See this example:

with open("Land_and_Ocean_summary.txt", "r") as f:
    list_of_lines = f.readlines()

    for line in list_of_lines:
        stripped_line = line.strip()
        split_line = stripped_line.split()
        if len(split_line) > 0:
            year = split_line[0]
            if year.isdigit() and int(year) >= 2000:
                print(line)
Related