这是我的问题:
在我的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所以我认为这就是为什么它们不在一条线路上)。提前谢谢!
答案 0 :(得分:1)
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()
答案 1 :(得分:0)
您正在使用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中的输出: