簡體   English   中英

使用 writerow 而不是 writerows 在 CSV 上寫入時,如何避免字符串的每個字符之間出現逗號?

[英]How to avoid commas between each character of a string when writing on a CSV with writerow and not writerows?

我有以下代碼:

with open('filename.csv',  'w', newline='', encoding='utf-8') as arquivo:
    escritor = writer(arquivo)
    linha = 'Summary'
    escritor.writerow(linha)

此代碼的 output 是 csv 文件,其中第一行以這種方式呈現:

在此處輸入圖像描述

我在 StackOverflow 上看到了類似的問題,解決方案總是使用writerow而不是writerows ,這是我已經在做的事情。 有人可以幫我解決這個問題嗎?

提前致謝!

您必須使用列表(即使您只有一個元素)

escritor.writerow( [ linha ] )

對於writerows ,您將需要行列表(即使您只有一行)

escritor.writerows( [ [linha] ] )

更詳細的writerow (不帶s

item = 'Summary'
row = [ item ]   # list with all elements in row (even if you have only one item)
escritor.writerow( row )

更詳細的writerows (帶s

item = 'Summary'
row = [ item ]      # list with all elements (even if you have only one item)
all_rows = [ row ]  # list with all rows (even if you have only one row)
escritor.writerows( all_rows )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM