微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么会出现错误消息异常:此文件已关闭

如何解决为什么会出现错误消息异常:此文件已关闭

1.我试图编写一个python代码获取每个子文件夹中文件的所有内容,并为每个内容文件内容)创建一个索引。可以成功获取每个文件的所有内容。但是,当我运行代码时,它总是显示错误消息异常:此文件关闭

2.这是为每个内容建立索引的代码,有人可以向我解释为什么会发生这种事情吗? 回溯:

python-input-49-38a47b2f8c0c> in <module>
     39 print(searcher)
     40 
---> 41 writers.commit(optimize=True)
     42 
     43 # from whoosh.query import *

~/.local/lib/python3.8/site-packages/whoosh/writing.py in commit(self,mergetype,optimize,merge)
    928         else:
    929             # Close segment files
--> 930             self._close_segment()
    931         # Write TOC
    932         self._commit_toc(finalsegments)

~/.local/lib/python3.8/site-packages/whoosh/writing.py in _close_segment(self)
    841     def _close_segment(self):
    842         if not self.perdocwriter.is_closed:
--> 843             self.perdocwriter.close()
    844         if not self.fieldwriter.is_closed:
    845             self.fieldwriter.close()

~/.local/lib/python3.8/site-packages/whoosh/codec/whoosh3.py in close(self)
    265         for writer in self._colwriters.values():
    266             writer.finish(self._doccount)
--> 267         self._cols.save_as_files(self._storage,self._column_filename)
    268 
    269         # If vectors were written,close the vector writers

~/.local/lib/python3.8/site-packages/whoosh/filedb/compound.py in save_as_files(self,storage,name_fn)
    295 
    296     def save_as_files(self,name_fn):
--> 297         for name,blocks in self._readback():
    298             f = storage.create_file(name_fn(name))
    299             for block in blocks():

~/.local/lib/python3.8/site-packages/whoosh/filedb/compound.py in _readback(self)
    276 
    277             yield (name,gen)
--> 278         temp.close()
    279         self._tempstorage.delete_file(self._tempname)
    280 

~/.local/lib/python3.8/site-packages/whoosh/filedb/structfile.py in close(self)
    121 
    122         if self.is_closed:
--> 123             raise Exception("This file is already closed")
    124         if self.onclose:
    125             self.onclose(self)

异常:此文件关闭

    import os
    import codecs

    import whoosh
    from whoosh.index import create_in
    from whoosh.fields import *
    from whoosh.qparser import QueryParser
    
    
    
    schema = Schema(title=TEXT(stored=True),path=ID(stored=True),content=TEXT,textdata=TEXT(stored=True))
    
    ix = create_in("folder",schema)
    filelist = []
    
    for root,dirs,files in os.walk("./test_result"):
        for file in files:
            #append the file name to the list
            filelist.append(os.path.join(root,file))
    
    #print all the file names
    
    writer = ix.writer()
    i = 0
    
    for name in filelist:
          
        i = i +1
        with codecs.open (name,"r",encoding='utf-8',errors='ignore') as myfile:
            text=myfile.read()
    #         print ("adding document "+name)
            writer.add_document(title="document "+name,path="folder",content=text,textdata=text)
            myfile.close()
            print(text)
            
        
    
    searcher = ix.searcher()
    print(searcher)
    
    writers.commit(optimize=True)

解决方法

with 语句处理资源管理,包括文件关闭。您可以阅读更多相关信息here

此代码:

f = open(file)
f.write("blablabla")
f.close

相当于:

with open(file) as f
    f.write("blablabla")

此异常是由于您尝试关闭已被 with 语句隐式关闭的文件所致。

你只需要删除这一行:

myfile.close()

编辑:

我只是解释了代码中的错误,但没有注意到注释中的更新。请更新问题本身,删除提到的行。

顺便说一句,我看到您使用了 writers.commit() 而不是 writer.commit(),请确保这不是一个错字,如果您的代码仍然无法正常工作,请更新您的问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。