繁体   English   中英

从 Python 2.7 中的 csv 文件中删除最后一行/页脚

[英]Stripping the last line/footer from a csv file in Python 2.7

import csv
import operator
import os
import sys

with open('test.csv', 'r') as cvsfile:
    f = csv.reader(csvfile, delimiter=',')
    for line in f:
        line = [line:-1]
        print (line)

======

尝试了上述我试图在排序之前从 csv 文件中删除最后一行。 我可以使用 next() 命令去除页眉,但无法去除页脚。

要删除第一行/最后一行,您可以将 csv.reader 转换为列表,然后在其上使用[1:-1] 例如:

import csv

with open('test.csv', 'r') as csvfile:
    f = csv.reader(csvfile, delimiter=',')
    
    for line in list(f)[1:-1]:  # [1:-1] to strip first/last line from csv
        print (line)

如果您正在处理一个大数据集, list(f)[1:-1]将立即将整个集合加载到内存中,然后制作该列表的副本,而不包含原始列表的第一个和最后一个元素。 要继续使用生成器,以便一次只将一行加载到内存中,

import csv
import operator
import os
import sys

curr = None
next_line = None
with open('test.csv', 'r') as cvsfile:
    f = csv.reader(csvfile, delimiter=',')
    next(f) # remove first line
    try:
        curr = next(f)
        next_line = next(f)
        while True:
            print(curr)
            curr = next_line
            next_line = next(f) 
    except StopIteration: 
        pass

暂无
暂无

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

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