用for循环将多列写入CSV文件
这段代码片段包含bpy。我正在尝试把数据写入一个三列的CSV文件。第一列是顶点索引,第二列是U 坐标,第三列是V 坐标。
下面是这一部分我目前的代码片段:
import csv
import os
import bmesh
import bpy
...
for vert in bm.verts:
with open(full_file_path, mode='w', newline='') as file:
writer = csv.writer(file)
for loop in vert.link_loops:
uv_coords = loop[uv_lay].uv
vert_ind = vert.index
u = uv_coords[0]
v = uv_coords[1]
data = [[vert_ind, u, v]]
writer.writerows(data)
如果你在意full_file_path变量,我知道它已经正确设置,因为数据确实被写入到指定的csv。变量uv_lay等于 "bm.loops.layers.uv.active"
我对把一个for循环嵌套在一个with语句里(再嵌套在一个for循环里)的整个过程感到困惑。当前的代码只记录了第一个顶点及其UV坐标。
这可能是什么原因导致的?
我的猜测是我没有正确使用循环,但具体是哪儿用错了我还不清楚。
解决方案
The nested sequence for ... with open() .... for looks wrong.
You almost certainly want both loops within the file resource manager,
giving a sequence of with open() ... for ... for ....
As written, if there's a dozen bm.verts then we re-write
the same file a dozen times, discarding the first eleven versions of it
since we're overwriting them.
看起来有问题的嵌套序列 for ... with open() .... for 看起来不对。
你几乎肯定希望把这两个循环都放在文件资源管理器中,
从而得到一个 with open() ... for ... for ... 的序列。
照这样写的话,如果出现十几个 bm.verts,我们会把同一个文件写入十几次,覆盖掉它之前的版本,因此前面的版本会被丢弃。
extra rows being written
data = [[vert_ind, u, v]]
writer.writerows(data)
Doing that within the innermost loop looks wrong. Likely in that spot you wanted:
在最内层循环中这么做看起来不对。
很可能在那个位置你想要的是:
data = [vert_ind, u, v]
writer.writerow(data)
Or just .writerow([vert_ind, u, v]),
as introducing a data local variable
doesn't buy us anything here.
或者就写成 .writerow([vert_ind, u, v]),
因为引入一个 data 局部变量在这里并不能带来任何好处。
tuple unpack
uv_coords = loop[uv_lay].uv ...
u = uv_coords[0]
v = uv_coords[1]
Rather than use cryptic and inconvenient [0], [1] subscripts, prefer this:
与其使用那些隐晦且不便的 [0]、[1] 下标,不如使用这个:
u, v = loop[uv_lay].uv
Also, I see no motivation for introducing a vert_ind local variable,
given that vert.index is already perfectly clear.
另外,我看不出引入一个 vert_ind 局部变量的动机,因为 vert.index 已经非常清楚。