【发布时间】:2020-04-08 10:09:58
【问题描述】:
我有一个如下所示的文件:
Solid ASCII
facet normal -6.275966e-02 3.134884e-02 -9.975362e-01
outer loop
vertex -4.624000e-01 5.000000e-01 -2.023656e-01
vertex -4.624742e-01 4.811628e-01 -2.029529e-01
vertex -5.000000e-01 5.000000e-01 -2.000000e-01
endloop
endface
我附上了一张照片来解释文本在行中的缩进。我只想阅读数字并填写有效的特定方式,但我管理的方式是:
with open (r'CamaSTL.txt','r+') as infile,\
open (r'CamaSTL2.txt','w') as outfile:
for line in infile:
line = infile.read()
line = line.replace("facet normal", "")
line = line.replace("outer loop", "")
line = line.replace("vertex","")
line = line.replace("endloop","")
line = line.replace("endfacet","")
line = line.replace("endsolid","")
outfile.write(line)
f = open('CamaSTL2.txt','r')
obj1_normal = []
obj1_v1 = []
obj1_v2 = []
obj1_v3 = []
array = []
n = []
for line in f:
line = line.rstrip()
if(line):
for x in line.split():
array.append(float(x))
i=0
while i < (len(array)):
n=[array[i],array[i+1],array[i+2]]
obj1_normal.append(n)
v1 =[array[i+3], array[i+4], array[i+5]]
obj1_v1.append(v1)
v2 =[array[i+6],array[i+7],array[i+8]]
obj1_v2.append(v2)
v3 =[array[i+9],array[i+10],array[i+11]]
obj1_v3.append (v3)
i +=12
for row in obj1_normal:
print (row)
删除单词,生成一个新文件,读取新的生成文件并按照我想要的方式放置数字。有没有办法不生成新文件,“跳过”这些单词的阅读,只阅读并附加数字?因为我要用我创建的数组进行算术运算,然后我会想以同样的方式保存(因为我需要在字符串开头的单词)
【问题讨论】:
-
您可以使用数据格式化文本以显示缩进 - 您不必为此添加图像。
-
为什么要将数据写入文件只是为了再次读取它?您应该创建包含所有行的新列表。并且您只能添加替换后不为空的行。当您使用
for line in infile时,您不必使用infile.read(),因为您已经在变量line中有行
标签: python arrays performance function text-files