[docs]classFile:def__init__(self,data:Union[io.BufferedIOBase,str],*,filename:Optional[str]=None,spoiler:bool=False,description:Optional[str]=None):self.spoiler=spoilerself.description=descriptionself._filename=filenameifisinstance(data,io.IOBase):ifnot(data.seekable()anddata.readable()):raiseValueError(f"File buffer {data!r} must be seekable and readable")ifnotfilename:raiseValueError("Filename must be specified when passing a file buffer")self.data:io.BufferedIOBase=dataself._original_pos=data.tell()self._owner=Falseelse:ifnotself._filename:self._filename=dataself.data=open(data,"rb")self._original_pos=0self._owner=Trueself._closer=self.data.closeself.data.close=lambda:Nonedef__str__(self)->str:returnself.filenamedef__repr__(self)->str:returnf"<File filename='{self.filename}'>"@propertydeffilename(self)->str:""" `str`: The filename of the file """returnf"{'SPOILER_'ifself.spoilerelse''}{self._filename}"
[docs]defreset(self,*,seek:Union[int,bool]=True)->None:""" Reset the file buffer to the original position """ifseek:self.data.seek(self._original_pos)
[docs]defclose(self)->None:""" Close the file buffer """self.data.close=self._closerifself._owner:self.data.close()
[docs]defto_dict(self,index:int)->dict:""" `dict`: The file as a dictionary """payload={"id":index,"filename":self.filename}ifself.description:payload["description"]=self.descriptionreturnpayload