Reputation: 11
For example, my txt file looks like this:
coke: 100
mineral water: 200
wine: 500
I just want python to read the numbers of each, thank you!
Upvotes: 0
Views: 184
Reputation: 27577
You can use the str.split()
method:
with open('file.txt', 'r') as f:
numbers = []
for line in f.readlines():
if ':' in line:
numbers.append(int(line.split(':')[1]))
You could even use a list comprehension:
with open('file.txt', 'r') as f:
numbers = [int(line.split(':')[1]) for line in f.readlines() if ':' in line]
If there will be lines of different format, you can try using the built-in re
module:
with open('file.txt', 'r') as f:
numbers = re.findall(r'\d+', f.read())
And you can convert the list of strings into integers using the built-in map()
method:
with open('file.txt', 'r') as f:
numbers = list(map(int, re.findall(r'\d+', f.read())))
Upvotes: 1