簡體   English   中英

如何使用Python將字符串寫入csv文件中的列

[英]How to write a string to a column in csv file using Python

我正在嘗試使用 csv 模塊將字符串寫入 csv 文件。 該字符串在 Excel 工作表中作為不同行中的單個字符而不是一個字段中的單個字符打印。

with open('test.csv', 'w',newline='') as f:
    writer=csv.writer(f)
    writer.writerow("hello")
    writer.writerow("bye")

輸出就像

 h     e     l      l     o         
 b     y     e      

我只是想要的是

你好

再見

另外我如何在不同的列中寫作? 沒有像 writerow() 那樣的 writecolumn()

為了分兩行輸出:

writer.writerow(["hello"])
writer.writerow(["bye"])

為了輸出兩列:

 writer.writerow(["hello","bye"])

添加到以前的答案,

如果你想用 csv.writerows() 函數做同樣的事情:

rows = ["apple", "banana", "mango", "orange"]

with open('test.csv', 'w',newline='') as f:
    writer=csv.writer(f)
    writer.writerows([[row] for row in rows])

那應該打印所有行,每行 1 列。

暫無
暫無

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

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