简体   繁体   English

从 CSV 输入 Python 中查找最后一行

[英]Find the last row from a CSV input Python

I didn't really find an example related to my question as I don't know Pandas so I post it here.我没有真正找到与我的问题相关的例子,因为我不知道 Pandas,所以我把它贴在这里。 Let me know if this is not clear or already have been responded.如果这不清楚或已经得到回应,请告诉我。

I have a CSV input which I import like this我有一个 CSV 输入,我像这样导入

def import_csv(csvfilename):
    data = []
    with open(csvfilename, "r", encoding="utf-8", errors="ignore") as scraped:
        reader = csv.reader(scraped, delimiter=',')
        row_index = 0
        for row in reader:
            if row:  # avoid blank lines
                row_index += 1
                columns = [str(row_index), row[0], row[1], row[2]]
                data.append(columns)

    return data

I index rows with input_rows (there is probably a better way for this?)我用 input_rows 索引行(可能有更好的方法?)

Input example :输入示例:

[['1',
  '[FirstValue]',
  'FirstText',
  'AB'],

 [...]

 ['12',
  "['LastValue']",
  "LastText",
  'YZ']]

I'm looking to get the last row of this insput list.我希望获得此输入列表的最后一行。 Is there a simple way to do that without iterating over all the rows ?有没有一种简单的方法可以在不迭代所有行的情况下做到这一点?

Thank you !谢谢 !

You can get the last element in an array like so:您可以像这样获取数组中的最后一个元素:

some_list[-1]

In fact, you can do much more with this syntax.事实上,您可以使用此语法做更多事情。 The some_list[-n] syntax gets the nth-to-last element. some_list[-n]语法获取倒数第 n 个元素。 So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc所以some_list[-1]得到最后一个元素, some_list[-2]得到倒数第二个,等等

So in your case, it would be:所以在你的情况下,它将是:

import csv    

def import_csv(csvfilename):
    data = []
    with open(csvfilename, "r", encoding="utf-8", errors="ignore") as scraped:
        reader = csv.reader(scraped, delimiter=',')
        for row in reader:
        if row:  # avoid blank lines
            row_index += 1
            columns = [str(row_index), row[0], row[1], row[2]]
            data.append(columns)
return data

data = import_csv(file_name)
last_row = data[-1]

Python supports negative indexing. Python 支持负索引。

your_list[-1] # Fetch the last value in your list.

Without knowing your use case and more about the data and how you typically access the data, it's hard to say what data structure would be better for you.如果不了解您的用例以及有关数据的更多信息以及您通常如何访问数据,则很难说哪种数据结构更适合您。

It's worth noting that csv.reader is an Iterator and doesn't contain your data until iterated through.值得注意的是csv.reader是一个 迭代器,在迭代之前不包含您的数据。 Same is true for the scraped opened I/O Stream object which is also an iterator.对于同样是迭代器的scraped打开的 I/O Stream 对象也是如此。 The question to "Can I get the last row without iterating through the file/data" is unfortunately no, unless there is a specific stream point that you know can jump to (using scraped.seek() ), then you will not be able to get the very last row until all the data have been iterated through.不幸的是,“我可以在不遍历文件/数据的情况下获取最后一行”的问题是否,除非您知道可以跳转到的特定流点(使用scraped.seek() ),否则您将无法获取最后一行,直到所有数据都被迭代。

Once you have consumed all the data however, you can retrieve in your code with data[-1] by means of negative indexing, ie returning the last row of the list .但是,一旦您使用了所有数据,您就可以在代码中使用data[-1]通过负索引检索,即返回list的最后一行。

Here is a related question that might be of interest to you , but again, the answers all consume the data (reading the entirety as a list) prior to allowing the reverse() operation, hence, all the data must be read through once at least. 这是一个您可能感兴趣的相关问题,但同样,在允许reverse()操作之前,答案都消耗了数据(将整个作为列表读取reverse() ,因此,所有数据必须在至少。

You could actually get the last line within in your with statment Since python support negative indexing you could just use您实际上可以在with 语句中获取最后一行由于 python 支持负索引,您可以使用

with open(csvfilename, "r", encoding="utf-8", errors="ignore") as scraped:
        final_line = scraped.readlines()[-1]
        

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

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