I have a problem reading numbers from a file that have word/letters, I want to skip the "word" part and only read the numbers and add them to the list.
File list.txt
Salad 5 1 0 0 2 1
This was my last attempt:
f = open('text.txt', 'r')
line = f.readline(14)
print(line)
Output:
Salad
This is what I want to output:
[5, 1, 0, 0, 2, 1]
CodePudding user response:
You can use .isnumeric()
:
with open("list.txt") as input_file:
words = input_file.readline().split()
result = [int(word) for word in words if word.isnumeric()]
print(result)
This outputs:
[5, 1, 0, 0, 2, 1]
CodePudding user response:
You can import re and use it to find the integers in the string.
The end result would be a list containing the numbers but with the string data type so I have to use a for loop to convert the items to integer data type.
import re
f = open('text.txt', 'r')
line = f.readline().strip()
k = re.findall('[0-9] ', line)
k = [int(i) for i in k]
print(k)