簡體   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