I am new to Python and am looking for something in Python that is equivalent to parsing files in Perl. I have a text file as follows.

Blah.txt
vcc = 2.6, clock = 1.5 Mhz
vcc = 2.7, clock = 1.6 Mhz
vcc = 2.8, clock = 1.7 Mhz
vcc = 2.9, clock = 1.8 Mhz

All I want to do is read the file in Python and parse out the vcc and clock numbers.

fileInput = open('blah.txt', 'r')
for line in fileInput:
	m = re.match("vcc:(.*)", line)
	if m > -1:
		##How to get value of vcc and clock here?

How would I get the value of vcc and clock in my code? For instance, for the first time my program runs through the file I just want to get out the vcc and clock info(2.6, 1.5).

One way with regex.

import re

with open('blah.txt') as f:
    for line in f:
        line = line.strip()
        result = re.findall(r'\d\.\d', line)
        print [float(i) for i in result]

'''Output-->
[2.6, 1.5]
[2.7, 1.6]
[2.8, 1.7]
[2.9, 1.8]
'''

Without re, if surely good format:

>>> blah = """vcc = 2.6, clock = 1.5 Mhz
vcc = 2.7, clock = 1.6 Mhz
vcc = 2.8, clock = 1.7 Mhz
vcc = 2.9, clock = 1.8 Mhz"""
>>> blah = [line.split() for line in blah.splitlines()]
>>> blah
[['vcc', '=', '2.6,', 'clock', '=', '1.5', 'Mhz'], ['vcc', '=', '2.7,', 'clock', '=', '1.6', 'Mhz'], ['vcc', '=', '2.8,', 'clock', '=', '1.7', 'Mhz'], ['vcc', '=', '2.9,', 'clock', '=', '1.8', 'Mhz']]
>>> blah_numbers = [(float(line[2].strip(',')), float(line[-2].strip(','))) for line in blah]
>>> blah_numbers
[(2.6, 1.5), (2.7, 1.6), (2.8, 1.7), (2.9, 1.8)]
>>>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.