簡體   English   中英

如何將字符串列表寫入 CSV 文件,列表中的每一項都在一個新行中?

[英]How do I write a list of strings to a CSV file, with each item of the list on a new row?

我有一個字符串列表如下:

sentence = ['this stuff', 'is not','that easy']

我想寫入一個 csv 文件,列表中的每一項都在不同的行上。

當我使用下面的代碼時,

with open(os.path.join(path, 'testlist.csv'), 'w') as my_file:
    f_writer = csv.writer(my_file)
    f_writer.writerow(sentence)

我得到以下 output:

this stuff,is not,that easy

如何將列表中的每個項目放在不同的行中?

write row 取一個列表並將其寫在一行中,如果您希望行中的元素在不同的行上,則用 , 分隔

一個一個地傳給他們

sentence = ['this stuff', 'is not','that easy']
with open(os.path.join(path, 'testlist.csv'), 'w') as my_file:
    f_writer = csv.writer(my_file)
    for s in sentence: f_writer.writerow([s])
    # f_writer.writerow(sentence)

由於其他人已經給了你一些答案,所以你在 Python 3.x 中的 go:

print (*sentence,sep='\n',file=open(os.path.join(path, 'testlist.csv'), 'w'))

或者在 Python 2.7 你可以這樣做:

print open(os.path.join(path, 'testlist.csv'), 'w'),"\n".join(sentence)

(以上都不需要 csv 模塊)

在你的例子中,我認為你可以改變

f_writer = csv.writer(my_file)

f_writer = csv.writer(my_file, delimiter='\n')

在真正的延伸中,您可能可以改為更改:

 f_writer.writerow(sentence)

 f_writer.writerows(list([x] for x in sentence))

快樂的Python!

這有效:

import pandas as pd
sentence = ['this stuff', 'is not','that easy']
sent = pd.Series(sentence)
sent.to_csv('file.csv', header = False)

1)在“句子”中使用列表

2)用“writerows”替換“writerow”

例如:

# Change 1
sentence = [['this stuff'], ['is not'],['that easy']]

with open(os.path.join(path, 'testlist.csv'), 'w') as my_file:
    f_writer = csv.writer(my_file)
# Change 2
    f_writer.writerows(sentence)

暫無
暫無

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

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