重复第一个列表索引值直到第二个循环 运行 并使用 Python 保存在 CSV 中

Repeat First List index value until second loop run and save in CSV using Python

List1 = ['ROLLER,abc','BOLT,s']

List2 = ['TYPE , ROL,','DMET, LENGTH, THRES Tgg, GRE B, HEAD X,']

我想像这样使用 python

将列表数据保存到 CSV 中
Heading 1 Heading 2
Roller,abc Type
Roller,abc Rol
Bolt,s DMET
Bolt,s Lenght
Bolt,s Thress tag
Bolt,s GRE B
Bolt,s Head X

没有 csv 模块的快速响应

这不是最好的方法!

list1 = ['ROLLER','BOLT']

list2 = ['TYPE , ROL','DMET, LENGTH, THRES Tgg, GRE B, HEAD X,']

file = open("test.csv", mode="w")
for i in range(len(list1)):
    for y in [_.strip() for _ in list2[i].split(",")]:
        file.write(list1[i] + "," + y+"\n")

file.close()

最好使用 open 作为带有 with 运算符的上下文管理器。 如果发生 IndexError 异常,它将关闭文件。

with open('filename.txt', 'w') as file:
    for i, col_1 in enumerate(List1):
        for col_2 in List2[i].split(','):
            file.write(f"{col_1},{col_2.strip()}\n")