scrapy Python关闭文件

tyu7yeag  于 2022-11-09  发布在  Python
关注(0)|答案(6)|浏览(194)

我需要关闭文件,但我不能这样做,因为我使用的是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(['Статус', 'Количество'])
nle07wnf

nle07wnf1#

您需要重构代码,以便代码捕获文件句柄;那么在完成后就可以轻松地对它调用.close()
但是一个更好的解决方案仍然是使用with open,它对异常也是健壮的。即使with块中的代码引发了一个异常,而这个异常在调用你的函数的代码中被捕获,文件也会被关闭。

def open_spider(self, spider):
    time = dt.now().strftime(TIME_FORMAT)
    file_path = self.results_dir / FILE_NAME.format(time)
    with open(file_path, 'w')  as handle:
        self.file = csv.writer(handle)
        self.file.writerow(['Статус', 'Количество'])

但是,您可能希望此时只写入open,并保存self.handle以便稍后关闭它-函数的名称和设计表明,您希望继续向self.file写入数据,然后才向self.handle.close()写入数据
理想情况下,也许您希望创建一个spider_writer对象,它 * 也 * 是一个上下文管理器,这样您就可以说

with spider_writer(filename) as writer:
     writer.write(...)
bfnvny8b

bfnvny8b2#

最好将函数 Package 在with下,而不是手动关闭文件。

def open_spider(self, spider):
    time = dt.now().strftime(TIME_FORMAT)
    file_path = self.results_dir / FILE_NAME.format(time)
    with open(file_path, 'w') as file:
        self.file = csv.writer(file)
        self.file.writerow(['Статус', 'Количество'])
kupeojn6

kupeojn63#

只需先定义open()

f = open(file_path, 'w')
self.file = csv.writer(f)
self.file.writerow(['Статус', 'Количество'])
f.close()

或者通过with使用上下文管理器,这种情况下不需要手动关闭

with open(file_path, 'w') as f:
    self.file = csv.writer(f)
    self.file.writerow(['Статус', 'Количество'])
cyej8jka

cyej8jka4#

关闭文件的最好方法是使用with语句。这样可以确保在with语句中的块退出时文件也会关闭,因此您不需要显式调用close()方法,而是在内部完成。例如:

with open(file_path, 'w') as ff:
    self.file = csv.writer(ff)
    self.file.writerow(['Статус', 'Количество'])
vsaztqbk

vsaztqbk5#

你可以使用“with”关键字来关闭文件。稍微重写一下,你就可以得到:

import csv

class A():
    def __init__(self):
        pass

    def open_spider(self, spider):
        time = "12_00_00"
        file_path= f"test_{time}.csv"

        #file_path = self.results_dir / FILE_NAME.format(time)

        with open(file_path, 'w') as csv_file:
            self.file = csv.writer(csv_file)
            self.file.writerow(['Статус'.encode("utf-8"), 'Количество'.encode("utf-8")])

a=A()
spider = 'fasdfsafd'
a.open_spider(spider)

此外,我必须编码你提供的字符串,因为它们不是ascii。使用时钟时间是你要修复的东西。

kkbh8khc

kkbh8khc6#

您可以执行f = open(file_path, 'w'),然后再执行csv.writer(f)

def open_spider(self, spider):
    time = dt.now().strftime(TIME_FORMAT)
    file_path = self.results_dir / FILE_NAME.format(time)
    f = open(file_path, 'w')
    self.file = csv.writer(f)
    self.file.writerow(['Статус', 'Количество'])
    f.close()

或者,您也可以使用self.f而非f来稍后关闭档案。
然而,还有另一种方法,那就是使用with结构。下面是它的工作原理:

with open(file_path, 'w') as f:
    # do something with the file f here

# here the file should be closed automatically

它工作的原因是python在进入with构造时调用f__enter__方法(什么也不做),然后在退出with构造时调用f__exit__方法(关闭文件)。

def open_spider(self, spider):
    time = dt.now().strftime(TIME_FORMAT)
    file_path = self.results_dir / FILE_NAME.format(time)
    with open(file_path, 'w') as f:
        self.file = csv.writer(f)
        self.file.writerow(['Статус', 'Количество'])

你应该使用with的原因是它是防异常的。这意味着如果异常出现在with构造中,它将关闭文件,并仅在此后引发异常。因此,即使在写入文件时出错,文件也将被关闭。

相关问题