manev
manev

Reputation: 63

Python 2.7 reading a new line in CSV and store it as variable

I am using the code below to read the last line of my csv. file which is constantly updated and is working great. I am receiving the last line and it is consisted of 11 values which are comma separated. It goes like:

10/16/16, -1, false, 4:00:00 PM, 4585 , .......etc

Now I want to take the values from column 6 and 9 for example and store them as two separate variables and later use them as a conditions. Is there simple way to add just few lines to the existing code to achieve this or i have to write a new code?

import time, os

#Set the filename and open the file
filename = 'Test.csv'
file = open(filename,'r')

#Find the size of the file and move to the end
st_results = os.stat(filename)
st_size = st_results[6]
file.seek(st_size)

while 1:`enter code here`
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(0.5)`enter code here`
        file.seek(where)
    else:
        print line, # already has newline

Upvotes: 1

Views: 210

Answers (1)

leoybkim
leoybkim

Reputation: 312

You certainly can just add a few line in there to get what you want. I would delim each line by comma using line.split(','). This will return an array like this ['10/16/16', '-1', 'false', '4:00:00 PM', '4585' ]. Then you can simply save the array at index 6 ~ 9 for your convenience and use it later in the code.

Ex)

while 1:`enter code here`
where = file.tell()
line = file.readline()
if not line:
    time.sleep(0.5)`enter code here`
    file.seek(where)
else:
    arr_line = line.split(',')
    var6 = arr_line[6]
    var7 = arr_line[7]
    var8 = arr_line[8]
    var9 = arr_line[9]

    # other code ...

    print line

Upvotes: 1

Related Questions