[docs]@restore_wrapper@functools.lru_cache(maxsize=16)defget_file_content_and_extension(file_path:os.PathLike)->Tuple[str,str]:""" Reads the content of a text file or compressed text file and returns its content along with the real extension (excluding compression extensions like .gz). Args: file_path (str): Path to the text file or compressed text file. Returns: tuple: A tuple containing the file content (str) and the real extension (str). """# Determine if the file is gzipped by checking the magic numberwithopen(file_path,"rb")asf:magic_number=f.read(2)ifmagic_number==b"\x1f\x8b":# It's a gzipped fileopen_func=lambdax:gzip.open(x,"rt")else:# It's a regular text fileopen_func=lambdax:open(x,"rt")# Get the real extension by removing compression suffixespath=Path(file_path)compression_suffixes=[".gz"]suffixes=path.suffixes# Remove compression extensions from the endreal_suffixes=[]forsinreversed(suffixes):ifs.lower()incompression_suffixes:continueelse:real_suffixes.insert(0,s)break# Stop after finding the real extensionreal_extension="".join(real_suffixes)ifreal_suffixeselse""# Read the content of the filewithopen_func(file_path)asf:content=f.read()returnstr(content),str(real_extension)
[docs]defdump_pickle(obj:Any,path:os.PathLike,level:int=5)->None:f,ext=os.path.splitext(path)assertextin(".pkl",".pkz",".gz",".npz")ifext==".npz":np.savez_compressed(path,**obj)else:ifext==".pkl":path=f+".pkz"warnings.warn(f"Write on '{path}'")withgzip.open(path,"wb",compresslevel=level)asfp:pickle.dump(obj,fp)