There are some methods that I love, one of them is map. Surely you already know!
Imagine that you want to read the line cpu in the file /proc/stat
The file looks similar to this:
cpu 5513 0 7271 2832299 15350 1 1327 0 0 0
cpu1 xxx xxx xxx xxx xxx xxx xxx
- We open the file with open and assign it to a file object with (‘as’)
- Loop the file object (st)
- If the line startswith(‘cpu ‘) then we continue. (I left a space on the right of cpu, because in the file also we have cpu1, cpu2, and I only need ‘cpu’.
- I assign the result of map. We split the line starting in index 1 and we map the elements executing float in every element.
with open('/proc/stat', 'r') as st:
for line in st:
if line.startswith('cpu '):
line_split = map(float, line.strip().split()[1:])
Other way to do it: with a list comprehension:
line_split = [ int(x) for x in line.strip().split()[1:] ]