简体   繁体   English

如何将CSV文件的最后一行读入我可以操作的列表(python)

[英]How to read last line of CSV file into a list that I can manipulate (python)

I wrote a small function that will return the last row of a csv file. 我写了一个小函数,它将返回csv文件的最后一行。 I can't for the life of me figure out how to store that row into a list or array to use after the function has completed. 我不能为我的生活弄清楚如何将该行存储到列表或数组中以在函数完成后使用。

import os
import csv
hello = []
def getLastFile(filename):
    distance = 1024
    with open(filename,'rb') as f:
        reader = csv.reader(f)
        reader.seek(0, os.SEEK_END)
        if reader.tell() < distance:
            reader.seek(0, os.SEEK_SET)
            lines = reader.readlines()
            lastline = lines[-1]
        else:
            reader.seek(-1 * distance, os.SEEK_END)
            lines = reader.readlines()
            lastline = lines[-1]
    return lastline

I have tried defining an empty list at the top, and appending lastline to that list, but I found that that was wrong. 我已经尝试在顶部定义一个空列表,并将lastline附加到该列表,但我发现这是错误的。 Right now the function returns a csv row, ex: 'a','b','c', how can I make the output of my function save this into a global list or array that I can then use? 现在该函数返回一个csv行,例如'a','b','c',如何将我的函数输出保存到我​​可以使用的全局列表或数组中? Thank you! 谢谢!

If you want the result of a function to be used elsewhere you have to actually call the function. 如果您希望在其他地方使用函数的结果,则必须实际调用该函数。 For instance: 例如:

def print_last_line(filename):
    print getLastFile(filename)

Additionally there's the problem of scope, where you must define anything you want to use within the function in the function itself. 此外还存在范围问题,您必须在函数本身的函数中定义要使用的任何内容。 For instance: 例如:

test = []
def use_last_line(filename):
    test.append(getLastFile(filename))  # This will error, because test is not in scope

def use_last_line(filename):
    test = []
    test.append(getLastFile(filename))  # This will success because test is in the function.

Specifically to do this for what I'm guessing you're trying to do above, you would want to just actually call the function and assign the result to your hello array: 特别要做到这一点,我猜你正在尝试上面做的,你会想要实际调用该函数并将结果分配给你的hello数组:

hello = getLastFile(filename)

you could open the CSV file as an array with numpy's genfromtxt and then slice the last row, or if you know the length of your file, it looks like 1024 in your example, you can use the skip_header keyword. 您可以将CSV文件打开为具有numpy的genfromtxt的数组,然后切片最后一行,或者如果您知道文件的长度,在示例中看起来像1024,则可以使用skip_header关键字。 ie

import numpy as np
data = np.genfromtxt(filename, delimiter=",",skip_header=1024)

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

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