简体   繁体   English

Python 2.7 在 CSV 中读取新行并将其存储为变量

[英]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.我正在使用下面的代码来读取我的 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.我收到最后一行,它由 11 个以逗号分隔的值组成。 It goes like:它是这样的:

10/16/16, -1, false, 4:00:00 PM, 4585 , .......etc 16 年 10 月 16 日,-1,假,下午 4:00:00,4585,......等

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.现在我想从第 6 列和第 9 列中获取值并将它们存储为两个单独的变量,然后将它们用作条件。 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

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(',') .我会使用line.split(',')用逗号line.split(',')每一行。 This will return an array like this ['10/16/16', '-1', 'false', '4:00:00 PM', '4585' ] .这将返回一个像这样的数组['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.然后您可以简单地将数组保存在索引 6 ~ 9 处以方便起见,并在稍后的代码中使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM