我正在尝试将列表写入csv文件,以便每行有x个值(值的数量是x的倍数)。我一直在寻找一个解决方案,我已经找到了很多方法来解决这个问题,但我似乎无法让代码完成我想要的工作。
这是我的假设例子...... 我试图压缩列表,这是一个列表列表,试图让它每行写入2个值。没有用;这就是发生的事情......
我希望.txt文件中的列表看起来像这样:
Chocolates,3
Novels,14
Pens,4
Smiles,78
但在我的编码中,它看起来像这样......
record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78']
我用它来拉链:
records = [record1[i:i+2] for i in range(0, len(record1), 2)]
prize = open("box.txt","w")
writer = csv.writer(prize)
writer.writerow(records)
但是,它在txt文件中看起来像这样
"['Chocolates', '3']","['4', '14']","['Pens', '4']","['Smiles', '78']"
我还尝试以不同的方式将列表写入文件...
prize = open("box.txt","w")
writer = csv.writer(prize)
for record in records:
writer.writerow(records)
prize.close()
但看起来像这样:
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
"['Chocolates', '3']","['hiii', '14']","['Pens', '4']","['Smiles', '78']"
我不知道我是在正确的轨道上,还是我的方法是正确的。我认为外观取决于列表的外观,但是,我开始相信这取决于我将其写入文件的方式。
感谢您的阅读。希望我的解释很清楚,如果不是,那就很抱歉。
答案 0 :(得分:1)
在第一种情况下,您应该使用writerows()
,而不是writerow()
:
writer.writerows(records)
在第二种情况下应该是:
for record in records:
writer.writerow(record) # record, not records
<强>演示强>
尝试将其粘贴到Python shell中:
import csv
record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78']
records = [record1[i:i+2] for i in range(0, len(record1), 2)]
with open("box.txt", "w") as prize:
writer = csv.writer(prize)
writer.writerows(records)
运行此代码后box.txt
包含:
Chocolates,3 Novels,14 Pens,4 Smiles,78
答案 1 :(得分:0)
prize = open("box.csv","w")
writer = csv.writer(prize)
writer.writerows(records)
答案 2 :(得分:0)
我希望你喜欢这个。
import csv
record1 = ['Chocolates', '3', 'Novels', '14', 'Pens', '4', 'Smiles', '78']
with open('box.csv', 'wb') as csvfile:
writer = csv.writer(csvfile)
for item, count in zip(record1[::2], record1[1::2]):
writer.writerow([item, count])