Skip to content Skip to sidebar Skip to footer

How Do I Use A Specific Line Of A Text File In Python?

My text file is this: 467 119 635 231 234 858 786 463 715 745 729 574 856 806 339 106 487 798 791 392 916 177 115 948 871 525 As you can see, there are three separate lines with d

Solution 1:

for line in f:
    nums = map(int, line.split())
    # looks at one line at a time, you can sort it now

If you want them all loaded at once

nums = [map(int, line.split()) for line in f]

Now you can access it like nums[0], nums[1] for each seperate line.


Solution 2:

This is a function that will do what you want. just give it the path to the file and it will do the rest.

Note: It is a generator.

def read_sort(file_path):
    with open(file_path) as f:
        for line in f:
            yield sorted(map(int, line.split()))


print list(read_sort(__path_to_file__)

Post a Comment for "How Do I Use A Specific Line Of A Text File In Python?"