从csv中删除最后一行

时间:2016-04-01 21:16:41

标签: python csv

我正在尝试在读取它之后从csv文件中删除最后一行,python 2.7但是我的代码无效..任何人都可以帮忙?

with open('eggs.csv', 'rb') as f:
    last_timestamp = f.readlines()[-1].split(",")[0]
    f.writerow()[-1]

Thannks !!

1 个答案:

答案 0 :(得分:1)

如果您正在使用csv文件,最佳解决方案是使用正确的工具

import csv

with open('eggs.csv','rb') as fh:
    mylist = []
    myreader = csv.DictReader(fh)
    headers = myreader.fieldnames
    for row in myreader:
       mylist.append(row)

所以你将拥有一个列表,其中每个元素都是一个字典。字典的关键是列标题,值是列

的行值

现在删除最后一行:

mylist = mylist[0:-1]

然后把它写回来

outref = open('eggs.csv','wb')
mywriter = csv.DictWriter(outref, fieldnames = headers)
headerdict = dict((col,col) for col in headers) # create a dict with col headings)
mywriter.writerow(headerdict) #writeout the column headings first
mywriter.writerows(mylist)    #write the data
outref.close()