繁体   English   中英

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

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

我写了一个小函数,它将返回csv文件的最后一行。 我不能为我的生活弄清楚如何将该行存储到列表或数组中以在函数完成后使用。

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

我已经尝试在顶部定义一个空列表,并将lastline附加到该列表,但我发现这是错误的。 现在该函数返回一个csv行,例如'a','b','c',如何将我的函数输出保存到我​​可以使用的全局列表或数组中? 谢谢!

如果您希望在其他地方使用函数的结果,则必须实际调用该函数。 例如:

def print_last_line(filename):
    print getLastFile(filename)

此外还存在范围问题,您必须在函数本身的函数中定义要使用的任何内容。 例如:

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.

特别要做到这一点,我猜你正在尝试上面做的,你会想要实际调用该函数并将结果分配给你的hello数组:

hello = getLastFile(filename)

您可以将CSV文件打开为具有numpy的genfromtxt的数组,然后切片最后一行,或者如果您知道文件的长度,在示例中看起来像1024,则可以使用skip_header关键字。

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