python 分离obj模型文件数据

今天在分离.obj模型数据时,遇到一个问题,就是每行数据存在换行符,导致末尾添加的符号出现在下一行的行首。因此,需要先删除末尾的换行符,再添加符号。

知识点

replace(a,b) 将a替换为b,比如,replace("\n"," ") ,换行符替换为空格
obj 文件数据
1. v 顶点坐标
2. vt 纹理坐标
3. vn 顶点法向量
4. f 面,包含顶点索引,格式:v/vt/vn

#!/usr/bin/env python3
# encoding: utf-8
# coding style: pep8
# ====================================================
#   Copyright (C)2020 All rights reserved.
#
#   Author        : xxx
#   Email         : [email protected]
#   File Name     : parse_obj.py
#   Last Modified : 2020-07-10 20:02
#   Description   :
#
# ====================================================

import sys
import os
import numpy as np

objFilePath = 'particles.obj'

f_v = open("./v.txt", "w")
f_v.seek(0)
f_v.truncate()  # 清空文件

f_vt = open("./vt.txt", "w")
f_vt.seek(0)
f_vt.truncate()  # 清空文件

f_f = open("./f.txt", "w")
f_f.seek(0)
f_f.truncate()  # 清空文件

with open(objFilePath) as file:
    points = []
    while 1:
        line = file.readline()
        if not line:
            break
        strs = line.split(" ")
        if strs[0] == "v":
            tmp = strs[1]+","+strs[2]+","+strs[3].replace("\n","")+','
            f_v.write(tmp)
        if strs[0] == "vt":
            tmp = strs[1]+","+strs[2].replace("\n","")+','
            f_vt.write(tmp)
        if strs[0] =="f":
            tmp = str(int(strs[1].split("/")[0])-1)+","+str(int(strs[2].split("/")[0])-1)+","+str(int(strs[3].split("/")[0])-1)+","
            f_f.write(tmp)

参考

猜你喜欢

转载自blog.csdn.net/zxcasd11/article/details/107318382