20
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonのCSV出力で、カンマが大量発生してしまう原因

Last updated at Posted at 2018-05-15

pythonのCSV出力を行う際に、カンマが大量発生してしまったりして上手くいかない事がある。
特に、複数行にわたるCSV出力を行いたい時によく遭遇する。
これは、writerowとwriterowsの使い方を間違えている事が原因。

出したいCSV

abcdeffghij
klmnopqrset

よくある間違いの例1

code1.py
import csv

output = ["abcdeffghij", "klmnopqrset"]

outf = open("test.csv", 'w', newline='')
writer = csv.writer(outf)
writer.writerow(output)
outf.close()
print("出力完了")
test.csv
abcdeffghij,klmnopqrset

csv.writerで改行を挿入する場合は、2次元配列を使用しなければならない。
今回のoutputは1次元配列なのでwriterowで問題ないが、改行が入らず1行で出力されてしまう。

よくある間違いの例2

code2.py
import csv

output = ["abcdeffghij", "klmnopqrset"]

outf = open("test.csv", 'w', newline='')
writer = csv.writer(outf)
writer.writerows(output)
outf.close()
print("出力完了")
test.csv
a,b,c,d,e,f,g,h,i,j
k,l,m,n,o,p,q,r,s,t

1次元配列に対してwriterowsを使用してしまうと、改行は挿入されるものの、各文字列に対してカンマが大量挿入されてしまう。

正しい例

code3.py
import csv

output = [["abcdeffghij"], ["klmnopqrset"]]

outf = open("test.csv", 'w', newline='')
writer = csv.writer(outf)
writer.writerows(output)
outf.close()
print("出力完了")
test.csv
abcdeffghij
klmnopqrset

writerowsを使用する場合は、対象を2次元配列にすることを忘れずに。
ちなみに、空配列を置くことで空白行も挿入する事も出来る。

20
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?