gpt4 book ai didi

python - 将 x 个值写入 txt 文件中的每一行

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:34 25 4
gpt4 key购买 nike

我目前正在尝试将列表写入 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']"

我不知道我是否走在正确的道路上,或者我的方法是否正确。我认为外观取决于列表的外观,但是,我开始相信它取决于我将其写入文件的方式。

感谢您的阅读。希望我的解释很清楚,如果不是很抱歉。

最佳答案

在第一种情况下,您应该使用 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,3Novels,14Pens,4Smiles,78

关于python - 将 x 个值写入 txt 文件中的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42078933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com