我是编程的初学者,甚至是 Python 的初学者(我可以用 c++ 做一些基本的东西......)
我正在编写一个朋友不久前为我制作的代码,我想将其输出存储在一个文件中,我认为一个.txt
文件非常适合我想做的事情。
您将在下面找到 2 个代码,
第一个有效,但仅在 pythonwin 的交互式窗口中打印数据(我使用的是 windows 7 和 python 2.7)。
它打印出类似的东西,这对我的项目很有用:
thrown out: bTUD, K2, MAG B, K1C, K1B, K1A, XTC64 II, REF , LBK, MAG C
1 1 : ['PINKwA', 'GB', 'PINK', 'TUwA'] [ 0.23994351 0.61419796 0.00956974 0.1362888 ] tet_i 66
1 2 : ['PINKwA', 'GB', 'PINK', 'TUwA'] [ 0.23816363 0.61917833 0.01219634 0.13046169] tet_i 66
1 3 : ['PINKwA', 'GB', 'PINK', 'TUwA'] [ 0.23638376 0.6241587 0.01482295 0.12463459] tet_i 66
1 4 : ['PINKwA', 'GB', 'PINK', 'TUwA'] [ 0.23460388 0.62913907 0.01744955 0.11880749] tet_i 66
1 5 : ['PINKwA', 'GB', 'PINK', 'TUwA'] [ 0.23282401 0.63411944 0.02007616 0.11298039] tet_i 66
...etc.
第二个代码是我尝试使用这些功能output
,output.write
但它根本不起作用!我缺少 python 的基本语言技能,我想这就是为什么我无法找出解决方案的原因。
第一个代码(打印功能正常)
import tetgen, geometry
from pprint import pprint
import random, csv
import numpy as np
from pprint import pprint
all_colors = [(name, float(X), float(Y), float(Z))
for name, X, Y, Z in csv.reader(open('colors.csv'))]
# background is marked SUPPORT
support_i = [i for i, color in enumerate(all_colors) if color[0] == 'SUPPORT']
if len(support_i)>0:
support = np.array(all_colors[support_i[0]][1:])
del all_colors[support_i[0]]
else:
support = None
tg, hull_i = geometry.tetgen_of_hull([(X,Y,Z) for name, X, Y, Z in all_colors])
colors = [all_colors[i] for i in hull_i]
print ("thrown out: "
+ ", ".join(set(zip(*all_colors)[0]).difference(zip(*colors)[0])))
targets = [(name, float(X), float(Y), float(Z), float(BG))
for name, X, Y, Z, BG in csv.reader(open('targets.csv'))]
for target in targets:
name, X, Y, Z, BG = target
target_point = support + (np.array([X,Y,Z]) - support)/(1-BG)
tet_i, bcoords = geometry.containing_tet(tg, target_point)
if tet_i == None:
print "out"
# not in gamut
else:
names = [colors[i][0] for i in tg.tets[tet_i]]
print "%s:" % target[0], names, bcoords, "tet_i", tet_i
编辑:下面的代码有效,但只导出文件中的一行数据
for target in targets:
name, X, Y, Z, BG = target
target_point = support + (np.array([X,Y,Z]) - support)/(1-BG)
tet_i, bcoords = geometry.containing_tet(tg, target_point)
if tet_i == None:
output = open('output.txt','a')
output.write(str(target[0]))
else:
output = open('output.txt','a')
names = [colors[i][0] for i in tg.tets[tet_i]]
output.write(str(target[0]))
output.write(str(names))
output.write(str(bcoords))
你能帮我找出如何将这些数据写入文件吗?