简体   繁体   中英

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. 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. 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? 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 = 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. ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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