python-3.x 无法将字符加入csv编写器中的字符串

sd2nnvve  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(173)

我想把我的结果保存到csv文件。这是我的代码:

import itertools
import csv

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

combinations = list(itertools.permutations(letters, 4))
print(len(combinations))

with open('result.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for item in combinations:
        wr.writerow("".join(item))
    myfile.close()

.csv结果为:

"A","B","C","D"
"A","B","C","E"
"A","B","C","F"
...

我期待的是

"ABCD"
"ABCE"
"ABCF"
...

我是python新手,但我不知道为什么会发生这种情况,因为当我在循环中写"".join(item)时,我得到了我想要的。你能帮助我吗?
我期待的是:

"ABCD"
"ABCE"
"ABCF"
...
68de4m5k

68de4m5k1#

问题是你传递给writerrow的是一个字符串而不是一个列表。要解决这个问题,你可以在将.join(item)传递给writerrow之前将它 Package 在一个列表中。下面是修改后的代码:

import itertools
import csv

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

combinations = list(itertools.permutations(letters, 4))
print(len(combinations))

with open('result.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for item in combinations:
        wr.writerow(["".join(item)]) # wrap "".join(item) inside a list
    myfile.close()

这将在CSV文件中给予所需的输出。

6tr1vspr

6tr1vspr2#

writerrow()将传入的字符串解释为字符序列。这会导致函数将每个字符作为单独的字段写入。您可以不传入"".join(item),而是传入["".join(item)]以将它们视为单个字段

import itertools
import csv

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

combinations = list(itertools.permutations(letters, 4))
print(len(combinations))

with open('result.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for item in combinations:
        wr.writerow(["".join(item)])
    myfile.close()

相关问题