如何使用Python提取100GB txt文件数据并按指定格式输出
Python实现超大txt文件格式转换方案
注意:由于文件大小达100GB,绝对不能一次性将整个文件加载到内存,必须采用逐行流式读写的方式处理,避免内存溢出。
完整实现代码
def process_large_txt(input_path: str, output_path: str) -> None: # 上下文管理器自动处理文件资源释放 with open(input_path, 'r', encoding='utf-8') as in_f, open(output_path, 'w', encoding='utf-8') as out_f: # 逐行遍历文件,每次仅加载单行数据到内存 for line in in_f: line = line.strip() # 跳过空行 if not line: continue # 去除行首尾的括号 content = line.strip('()') # 分割字段,最多分割5次避免末尾多余逗号干扰 fields = [f.strip().strip("'") for f in content.split(',', maxsplit=5)] # 提取字段,空值替换为None list_num, type_, race, age, hair_color, sex = fields race = race if race else 'None' sex = sex.rstrip(',') # 处理字段末尾多余的逗号 # 格式化写入输出文件 out_f.write(f"List number: {list_num:<14} Age: {age}\n") out_f.write(f"Type: {type_:<19} Hair Color: {hair_color}\n") out_f.write(f"Race: {race:<19} Sex: {sex}\n") out_f.write("-------------------------------------------------------\n") if __name__ == "__main__": # 替换为实际的输入输出文件路径即可运行 process_large_txt("input.txt", "output.txt")
代码说明
- 内存占用稳定在KB级,完全适配100GB级超大文件处理需求
- 字段分割添加
maxsplit=5参数,适配你提供的示例中字段末尾多余逗号的特殊格式 - 格式化采用左对齐参数保证输出列对齐,和你要求的输出格式完全匹配
- 自动将空的Race字段替换为指定的
None值
可选优化点
- 如需提升处理速度,可将文件按字节分块后用多进程并行处理,注意做好块边界的行截断兼容
- 若源文件编码非utf-8,可修改
open方法的encoding参数适配(如gbk、latin-1等)
内容的提问来源于stack exchange,提问作者Leo ley
相关产品推荐
相关产品推荐

