Search code examples
pythonlistfiletext

Remove line numbers from text file and extract values to list


I have a txt file with some data but they are have line number annotations, how can I easily go from this to list with only the numbers on the right?

1   3.170

2   3.198

3   3.188

4   3.153

5   3.164

6   3.214

7   3.095

8   3.078

9   3.193

10  3.113

I've done it in 3 steps:

with open('numbers', 'r') as file:
    for line in file:
        for word in line.split():
            print(word)

then with the result

with open('main.py') as f:
    lines = f.read().splitlines()
print(lines)

Then I sorted the numbers and just copied the value between 3 and 4:

numbers = ('1', '3.170', '2', '3.198', '3', '3.188', '4', '3.153', '5', '3.164', '6', '3.214', '7', '3.095', '8', '3.078', '9', '3.193', '10', '3.113', '11', '3.153', '12', '3.119')
float_lst = [float(item) for item in numbers]
sor = sorted(float_lst)
print(sor)

How can I make it work?


Solution

  • Just discard the line numbers as you go.

    with open('numbers', 'r') as file:
        numbers = [float(line.rstrip('\n').split()[1]) for line in file]
    

    If the list comprehension seems intimidating, here's a longhand version:

    numbers = []
    with open('numbers', 'r') as file:
        for line in file:
            # Trim trailing newline
            line = line.rstrip('\n')
            # Extract last item
            item = line.split()[1]
            # Convert to float, add to list
            numbers.append(float(item))
    

    As a general principle, don't carry with you data that you don't need.

    If some lines could be empty, you can add an if not line: continue condition in the longhand version after removing the newline.

    numbers = []
    with open('numbers', 'r') as file:
        for line in file:
            # Trim trailing newline
            line = line.rstrip('\n')
            # Skip empty lines
            if not line:
                continue
            # Extract last item
            item = line.split()[1]
            # Convert to float, add to list
            numbers.append(float(item))