gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:54:44 24 4
gpt4 key购买 nike

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

reader.seek(0, os.SEEK_END)
AttributeError: '_csv.reader' object has no attribute 'seek'

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

有人可以帮我修改我的代码吗?我很确定您可以通过这种方式使用 seek,也许我错了?

最佳答案

这里是问题 Have csv.reader tell when it is on the last line 的已接受答案中核心概念的细微变化。适用于您对问题的变体。由于每一行的长度可能不同,因此实际上没有办法读取整个文件。

import csv

def get_last_row(csv_filename):
with open(csv_filename, 'r') as f:
lastrow = None
for lastrow in csv.reader(f): pass
return lastrow

更新

这是使用 collections.deque 进行此操作的更简单且可能更快的方法.我从问题的答案之一得到了这个想法 How to read an output line containing a list of integers produced .

from collections import deque
import csv

def get_last_row(csv_filename):
with open(csv_filename, 'r') as f:
try:
lastrow = deque(csv.reader(f), 1)[0]
except IndexError: # empty file
lastrow = None
return lastrow

关于python - 尝试使用 seek() 获取 csv 文件的最后一行时出现 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20296955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com