如何使用 Python 将多行合并到以逗号分隔的 csv 中的单个单元格

How to merge multiple rows into single cell in csv separated by comma using Python

这是我的问题:

在我的 csv 文件中,我只有一列和多行包含电话号码。

    a 
1  222
2  333
3  444
4  555

我想要的是将它们合并为一个字符串并用逗号分隔,例如:

   a
1  222,333,444,555

我现在使用的代码是:

import csv

b = open('test.csv', 'wb')
a = csv.writer(b)

s = ''
with open ("book2.csv", "rb") as annotate:
    for col in annotate:

        ann = col.lower().split(",")
        s += ann[0] + ','
s = s[:-1] # Remove last comma

a.writerow([s])
b.close()

我从中得到的是

   a
1   222,
    333,
    444,
    555

现在所有号码都在一个单元格中(很好)但它们不在一行中(每个电话号码后面有 /r/n,所以我认为这就是它们不在一行中的原因)。提前致谢!

import csv

b = open('test.csv', 'wb')
a = csv.writer(b)

s = ''
with open ("book2.csv", "rb") as annotate:
    for col in annotate:

        ann = col.lower().strip('\n').split(",")
        s += ann[0] + ','
s = s[:-1] # Remove last comma

a.writerow([s])
b.close()

您正在使用 csv 模块,但忽略了 csv.reader。它为您处理所有解析:

#!python2
import csv
with open('book2.csv','rb') as inf, open('test.csv','wb') as outf:
    r = csv.reader(inf)
    w = csv.writer(outf)
    L = [row for row in r] # Read all lines as list of lists.
    L = zip(*L)            # transpose all the lines.
    w.writerows(L)         # Write them all back out.

输入:

222
333
444
555

.csv 文件中的输出:

222,333,444,555

编辑: 我现在看到您希望 Excel 中的数据位于单个单元格中。以上将把它放在一行四个单元格中:

以下将写入单个单元格:

#!python2
import csv
with open('book2.csv') as inf, open('test.csv','wb') as outf:
    w = csv.writer(outf)
    data = inf.read().splitlines()
    w.writerow([','.join(data)])

.csv 文件中的输出:

"222,333,444,555"

Excel中的输出: