MCPcopy Create free account
hub / github.com/KnowledgeXLab/LeanRAG / read_txt_multithread

Function read_txt_multithread

tools/io_file.py:121–148  ·  view source on GitHub ↗

使用多线程读取大文本文件。 参数: - file_path (str): 文件路径。 - chunk_size (int): 文件大小阈值,单位为字节。 - encoding (str): 文件编码格式,默认为 'utf-8'。 返回: - str: 拼接后的文件内容。

(file_path, chunk_size, encoding='utf-8')

Source from the content-addressed store, hash-verified

119
120
121def read_txt_multithread(file_path, chunk_size, encoding='utf-8'):
122 """
123 使用多线程读取大文本文件。
124
125 参数:
126 - file_path (str): 文件路径。
127 - chunk_size (int): 文件大小阈值,单位为字节。
128 - encoding (str): 文件编码格式,默认为 'utf-8'
129
130 返回:
131 - str: 拼接后的文件内容。
132 """
133 file_size = os.path.getsize(file_path)
134 num_chunks = (file_size // chunk_size) + 1
135 logger.info(f"分割文件为 {num_chunks} 个块进行多线程读取")
136
137 # 获取合适的线程数
138 cpu_count = os.cpu_count() // 2 # 限制使用一半的CPU核心数
139 num_threads = min(cpu_count, num_chunks)
140
141 chunks = []
142 with ThreadPoolExecutor(max_workers=num_threads) as executor:
143 # 将文件分块读取并并行处理
144 futures = [executor.submit(read_chunk, file_path, i * chunk_size, (i + 1) * chunk_size, encoding) for i in range(num_chunks)]
145 for future in tqdm(futures, desc="读取文件进度"):
146 chunks.append(future.result())
147
148 return ''.join(chunks)
149
150
151def read_chunk(file_path, start, end, encoding='utf-8'):

Callers 1

read_txtFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected