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

求助:Python实现按f分隔提取纯v行生成多个文本文件

需求与问题

需要编写Python代码,从text.txt文件中提取仅以空格跟随字母v开头的行(即纯v行),并在每次遇到以字母f开头的行后,将后续的纯v行写入新的文本文件。

输入文件内容(text.txt)

v 123 123 123
v 123 123 123
v 123 123 123
vt 123 123 123
vn 123 123 123
f 12345 12345 12345
v 231 321 321
v 231 321 321
v 231 321 321
v 231 321 321
vt 321 312 321
vn 312 312 321
f 54321 54321 54321

当前问题

已实现提取所有纯v行到单个文件,但无法按f行分隔生成多个独立文件——每次遇到f行后,后续的纯v行需要存入新的文件。

现有代码

if is_obj:
    w = open("mid.txt", "w")
    r = open(f"object.obj", "r")
    def treat():
        if line[0] == 'v':
            if line[1] == ' ':
                w.write(line)
    with open(f'object.obj') as read:
        for i in read:
            for line in read:
                treat()

解决方案

实现思路

  1. 用计数器记录当前生成的文件序号
  2. 用列表临时存储当前段的纯v行
  3. 遍历输入文件的每一行:
    • 若为纯v行,加入临时列表
    • 若为f行,将临时列表中的内容写入对应序号的文件,清空列表并递增计数器
  4. 遍历结束后,处理最后一段未被f行触发写入的纯v行

完整代码

def split_v_lines_by_f(input_file="text.txt"):
    file_counter = 1
    current_v_lines = []
    
    with open(input_file, 'r') as infile:
        for line in infile:
            # 判断是否为纯v行:开头是v且紧随空格(兼容行首无空格的情况)
            if len(line) >= 2 and line[0] == 'v' and line[1] == ' ':
                current_v_lines.append(line)
            # 判断是否为f开头的行
            elif line.strip().startswith('f'):
                # 若当前有收集的v行,写入文件
                if current_v_lines:
                    with open(f"v_segment_{file_counter}.txt", 'w') as outfile:
                        outfile.writelines(current_v_lines)
                    current_v_lines = []
                    file_counter += 1
        # 处理最后一段无f行结尾的v行
        if current_v_lines:
            with open(f"v_segment_{file_counter}.txt", 'w') as outfile:
                outfile.writelines(current_v_lines)

# 执行函数
split_v_lines_by_f()

代码说明

  • 生成的文件命名为v_segment_1.txt、v_segment_2.txt等,按顺序对应每个f行分隔的纯v行段
  • 示例中v_segment_1.txt会包含前3行纯v行,v_segment_2.txt包含后续4行纯v行
  • 自动处理文件打开/关闭,避免资源泄漏

内容的提问来源于stack exchange,提问作者Mops Lops

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:25:38