使用多线程读取大CSV文件。 参数: - file_path (str): 文件路径。 - chunk_size (int): 文件大小阈值,单位为字节。 - encoding (str): 文件编码格式,默认为 'utf-8'。 返回: - DataFrame: 拼接后的CSV文件内容。
(file_path, chunk_size, encoding='utf-8')
| 188 | |
| 189 | |
| 190 | def read_csv_multithread(file_path, chunk_size, encoding='utf-8'): |
| 191 | """ |
| 192 | 使用多线程读取大CSV文件。 |
| 193 | |
| 194 | 参数: |
| 195 | - file_path (str): 文件路径。 |
| 196 | - chunk_size (int): 文件大小阈值,单位为字节。 |
| 197 | - encoding (str): 文件编码格式,默认为 'utf-8'。 |
| 198 | |
| 199 | 返回: |
| 200 | - DataFrame: 拼接后的CSV文件内容。 |
| 201 | """ |
| 202 | file_size = os.path.getsize(file_path) |
| 203 | num_chunks = (file_size // chunk_size) + 1 |
| 204 | logger.info(f"分割文件为 {num_chunks} 个块进行多线程读取") |
| 205 | |
| 206 | cpu_count = os.cpu_count() // 2 # 限制使用一半的CPU核心数 |
| 207 | num_threads = min(cpu_count, num_chunks) |
| 208 | |
| 209 | data_chunks = [] |
| 210 | with ThreadPoolExecutor(max_workers=num_threads) as executor: |
| 211 | futures = [executor.submit(read_csv_chunk, file_path, i * chunk_size, (i + 1) * chunk_size, encoding) for i in range(num_chunks)] |
| 212 | for future in tqdm(futures, desc="读取CSV进度"): |
| 213 | data_chunks.append(future.result()) |
| 214 | |
| 215 | return pd.concat(data_chunks, ignore_index=True) |
| 216 | |
| 217 | |
| 218 | def read_csv_chunk(file_path, start, end, encoding='utf-8'): |