Home > other >  Python Extract Numbers from a file
Python Extract Numbers from a file

Time:03-04

So, I have a txt file with some integers which are between 0 and 50. I want to extract them and to use their values. The txt file looks like:

1 2 40 23

2 34 12

3 12 1

I have tried something like:

with open(input_file, "r") as file:
    lines = file.readlines()
    for i in range(len(lines)):
        l = lines[i].strip()
        for c in range(1, len(l)-1):
            if(l[c] >= '0' and l[c] <= '9' and (l[c 1] < '0' or l[c 1] > '9')):
                # other code with those numbers
            elif(l[c] >= '0' and l[c] <= '9' and (l[c 1] >= '0' and l[c 1] <= '9')):
                # other code with those numbers

The problem is that I extract the two digits numbers, but I do also extract one digit two digits numbers.

Any solution?

CodePudding user response:

Or this way:

my_array=[]
with io.open(inputfile, mode="r", encoding="utf-8") as f:             
    for line in f:
        my_array=my_array line.split()
results = list(map(int, myarray)) #convert to int    
print(my_array)

Output:

[1, 2, 40, 23, 2, 34, 12, 3, 12, 1]

CodePudding user response:

You can gather all the numbers in the file into a list like this:

import re

with open(input_file) as f:
    print(list(map(int, re.findall('\d ', f.read()))))

Output:

[1, 2, 40, 23, 2, 34, 12, 3, 12, 1]

Note:

Use of re may be unnecessary in OP's case but included here because it allows for potential garbage in the input file

  • Related