Reputation: 29
I have a problem where I need to read an unknown amount of lines from a text file, and determine whether or not the lines are in ascending order. Any help would be much appreciated.
Upvotes: 0
Views: 1644
Reputation: 4130
If your file looks something like this:
alphabet
bee
house
part
wine
And you want to check if the lines are in lexicographic order, you can use something simple like this:
lines = open("myfile.txt", "r").read().splitlines()
if sorted(lines) == lines:
print("File is in the correct order.")
All this does is open the file, separates it into individual lines, and compares the lexicographical order to the actual order. You can do this because Python sorts lexicographically, as seen here:
Upvotes: 2