ValueError: I/O operation on closed file 解决办法
报错:ValueError: I/O operation on closed file
- ValueError: I/O operation on closed file。是指处理了已经被关闭的数据。一般是语句没有对齐。当python的处理代码不对齐的时候会出现这种情况。
 - 使用with方法打开了文件,生成的文件操作实例在with语句之外是无效的,因为with语句之外文件已经关闭了。
 
报错部分代码:
class Maoyan(object):
	...
    def run(self):
        response = self.get_data()
        datas = self.parse_data(response)
        self.save_data(datas)
if __name__ == '__main__':
	...
    with open('猫眼.csv', 'a', newline='', encoding="utf8") as f:
        csv_writer = csv.writer(f)
        csv_writer.writerow(head)
    maoyan = Maoyan()
    maoyan.run()
 
解决:
检查了很多遍,因为已经确认了是缩进的问题,最后才发现最后两行代码也要缩进,因为调用的保存也要在with语句块里能有效。

 改成图片里这样就可以运行了!
