我试图从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)
有人可以帮我修改我的代码吗?我很确定你可以用这种方式使用搜索,也许我错了?
我试图从CSV文件中提取一堆行并将它们写入另一行,但我遇到了一些问题.
import csv
f = open("my_csv_file.csv", "r")
r = csv.DictReader(f, delimiter=',')
fieldnames = r.fieldnames
target = open("united.csv", 'w')
w = csv.DictWriter(united, fieldnames=fieldnames)
while True:
try:
row = r.next()
if r.line_num <= 2: #first two rows don't matter
continue
else:
w.writerow(row)
except StopIteration:
break
f.close()
target.close()
Run Code Online (Sandbox Code Playgroud)
运行此,我收到以下错误:
Traceback (most recent call last):
File "unify.py", line 16, in <module>
w.writerow(row)
File "C:\Program Files\Python25\lib\csv.py", line 12
return self.writer.writerow(self._dict_to_list(row
File "C:\Program Files\Python25\lib\csv.py", line 12
if k not in self.fieldnames:
TypeError: argument of type 'NoneType' …Run Code Online (Sandbox Code Playgroud) 我想迭代文件的行,并为每个文件打印一些输出.,\n除最后一行外,所有打印的行最后都应该有一行.
我的第一种方法是使用查找hasNext()不存在的方法.我知道StopIteration引发了异常,但我不确定如何以Pythonic的方式使用它来实现我想要的.