0

New to python and stuck on reading a file...

I want to search a file for data using python3.

I have a data file that looks like this:

hostname,timestamp,#of CPUs,memory,cpu,disk

hostname1,07311906,1,4.84%,74%,0.45%
hostname2,07311906,2,3.84%,24%,0.45%
hostname1,07311907,1,4.85%,74%,0.49%
hostname2,07311907,2,4.64%,44%,0.30%
hostname1,07311908,1,5.20%,74%,0.78%
hostname2,07311908,2,4.44%,54%,0.40%

I'd like to cycle through a config file like this pseudo code:

for i in server.list do
   <graph the data server i for the month of `date %m`>
 done

The end goal is loop through my data file and do processing for each server in a list.

1 Answer 1

1

You can use with open() in python like this:

with open(filename, 'r') as fileContent:
    listOfLines = fileContent.readlines()

Now you will have a list of every line inside of the file. Probably also helpful would be:

for row in listOfLines:
    curData = row.split(',')

This will split the content of the row at every "," and return a list. After that you can work with the data.

3
  • Thanks. I like it. But why does it do this? ['hostname1', '07311910', '1', '4.85%', '74%', '0.13%\n'] ??? Seems like it gets the last line, Now I wonder how I am going to pull out each value from that string...
    – Marinaio
    Commented Jul 31, 2019 at 14:54
  • Since in this line: for row in listOfLines: you iterate over every line, so anything you want to do you need to do inside of the loop. If you only check curdata after the loop it will have the last entry since it iterated over all lines. Instead you could append curData to a new list so you have all lines. @Marinaio Commented Aug 1, 2019 at 6:09
  • Also its not a string, its a list. So if you want to access the hostname for example you would write: hostname = curData[0] 0 here is the index of the list. So to access the second part you write curData[1] and so on Commented Aug 1, 2019 at 6:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.