小编The*_*ool的帖子

尝试使用seek()获取csv文件的最后一行时的AttributeError

我试图从csv文件返回最后一行.我正在修改我之前写的另一个函数,它返回文本文件的最后一行.它似乎首先按预期工作,但现在当我调用该函数时它会抛出一个错误.

reader.seek(0, os.SEEK_END)
Run Code Online (Sandbox Code Playgroud)
AttributeError: '_csv.reader' object has no attribute 'seek'
Run Code Online (Sandbox Code Playgroud)
import os
import csv
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
Run Code Online (Sandbox Code Playgroud)

有人可以帮我修改我的代码吗?我很确定你可以用这种方式使用搜索,也许我错了?

python csv seek

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

csv ×1

python ×1

seek ×1