You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:用Python从file_1读取完整交易内容并写入file_2

实现方案

没问题,这是一个简洁可靠的Python脚本,能帮你完成从file_1提取指定交易内容并写入file_2的需求:

# 定义文件名
input_file = "file_1"
output_file = "file_2"

# 标记是否开始写入交易内容
start_writing = False

# 使用with语句自动管理文件资源,避免手动关闭的麻烦
with open(input_file, 'r', encoding='utf-8') as f_in, open(output_file, 'w', encoding='utf-8') as f_out:
    for line in f_in:
        # 检查当前行是否以指定开头
        if line.startswith("Actual Transaction is "):
            start_writing = True
        # 如果已经开始写入,就把当前行写入输出文件
        if start_writing:
            f_out.write(line)

代码说明:

  • 上下文管理器with:自动处理文件的打开和关闭,即使脚本中途出错也能保证文件安全关闭,避免资源泄漏。
  • 起始行判断:用startswith()精准匹配交易内容的开头行,找到后开启写入标记。
  • 编码指定:显式设置encoding='utf-8',避免不同系统下的中文或特殊字符乱码问题。

额外提示:

  • 如果你的file_1和脚本不在同一个目录下,记得把input_file和output_file改成绝对路径(比如"C:/Documents/file_1"或者"/home/user/file_1")。
  • 如果文件中可能存在多个以"Actual Transaction is "开头的行,这个脚本会提取第一个匹配行及之后的所有内容;如果你只需要提取约100行,可以在写入时加个计数器,比如:
    count = 0
      with open(input_file, 'r', encoding='utf-8') as f_in, open(output_file, 'w', encoding='utf-8') as f_out:
          for line in f_in:
              if line.startswith("Actual Transaction is "):
                  start_writing = True
              if start_writing:
                  f_out.write(line)
                  count += 1
                  # 写入100行后停止
                  if count >= 100:
                      break
    

内容的提问来源于stack exchange,提问作者p.Dhaval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:22:04