我需要关闭文件,但我不能这样做,因为我使用的是csv.writer,我如何才能关闭文件?python
def open_spider(self, spider):
time = dt.now().strftime(TIME_FORMAT)
file_path = self.results_dir / FILE_NAME.format(time)
self.file = csv.writer(open(file_path, 'w'))
self.file.writerow(['Статус', 'Количество'])
6条答案
按热度按时间nle07wnf1#
您需要重构代码,以便代码捕获文件句柄;那么在完成后就可以轻松地对它调用
.close()
。但是一个更好的解决方案仍然是使用
with open
,它对异常也是健壮的。即使with
块中的代码引发了一个异常,而这个异常在调用你的函数的代码中被捕获,文件也会被关闭。但是,您可能希望此时只写入
open
,并保存self.handle
以便稍后关闭它-函数的名称和设计表明,您希望继续向self.file
写入数据,然后才向self.handle.close()
写入数据理想情况下,也许您希望创建一个
spider_writer
对象,它 * 也 * 是一个上下文管理器,这样您就可以说bfnvny8b2#
最好将函数 Package 在
with
下,而不是手动关闭文件。kupeojn63#
只需先定义
open()
或者通过
with
使用上下文管理器,这种情况下不需要手动关闭cyej8jka4#
关闭文件的最好方法是使用
with
语句。这样可以确保在with
语句中的块退出时文件也会关闭,因此您不需要显式调用close()方法,而是在内部完成。例如:vsaztqbk5#
你可以使用“with”关键字来关闭文件。稍微重写一下,你就可以得到:
此外,我必须编码你提供的字符串,因为它们不是ascii。使用时钟时间是你要修复的东西。
kkbh8khc6#
您可以执行
f = open(file_path, 'w')
,然后再执行csv.writer(f)
。或者,您也可以使用
self.f
而非f
来稍后关闭档案。然而,还有另一种方法,那就是使用
with
结构。下面是它的工作原理:它工作的原因是python在进入
with
构造时调用f
的__enter__
方法(什么也不做),然后在退出with
构造时调用f
的__exit__
方法(关闭文件)。你应该使用
with
的原因是它是防异常的。这意味着如果异常出现在with
构造中,它将关闭文件,并仅在此后引发异常。因此,即使在写入文件时出错,文件也将被关闭。