0
1

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 1 year has passed since last update.

Pythonでcsvにスペース区切りのリストを書き込む

Posted at

実現したいこと

リストを含むcsvをつくりたい ↓

hoge.csv
a, b, [1 2 3], c

結論

これで実現できます。

hoge.py
l = [1, 2, 3]  # リスト
l = '[' + ' '.join([str(x) for x in l]) + ']'  # リストをあらかじめ文字列にする!
row = ['a', 'b', l, 'c']  # csvの1行

# csvに出力
with open('hoge.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(row)

失敗した方法

愚直に書いたコード ↓

hoge.py
l = [1, 2, 3]  
row = ['a', 'b', l, 'c']  # csvの1行

# csvに出力
with open('hoge.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(row)
hoge.csv
a,b,"[1, 2, 3]",c
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?