简体   繁体   English

csv.writerow写到列而不是行

[英]csv.writerow writes to columns not rows

I have a Python test file which is a list of strings that I am trying to export into a csv file so that each word in the string is in a single column in the csv file. 我有一个Python测试文件,该文件是要尝试导出到csv文件中的字符串的列表,以便该字符串中的每个单词都在csv文件中的单个列中。 However my code places each word into a separate column within a single row. 但是我的代码将每个单词放在一行中的单独列中。 I have read others comments regarding similar issues on this site and they suggested changing the syntax to wr.writerows([csv_data]) . 我已经在该网站上阅读了有关类似问题的其他评论,他们建议将语法更改为wr.writerows([csv_data]) This modification does not work on the code below. 此修改不适用于以下代码。 I am a beginner at Python so would greatly appreciate any suggestions on how to fix this. 我是Python的初学者,因此非常感谢任何有关解决此问题的建议。

testfile=['free', 'great', 'congratulations', 'great', 'kind', 'freedom']

import csv
with open("pos_words_pre.csv",'w') as resultFile_pos_pre:
    wr_pos_pre = csv.writer(resultFile_pos_pre)
    wr_pos_pre.writerow(testfile)

Thank you very much for the help 非常感谢你的帮助

EDIT: The code above will place all the words in a csv file in the same row such as: 编辑:上面的代码将所有单词放在csv文件的同一行中,例如:
free, great, congratulations, great, kind, freedom 自由,伟大,祝贺,伟大,善良,自由

But I'm trying to create a file that has each entry in the same column but a separate row such as: 但是我正在尝试创建一个文件,该文件的每个条目都在同一列中,但在单独的行中例如:

free
great
congratulations
great
kind
freedom

I though that writerow will write each entry into a separate row in an excel csv file rather than the same row. 我虽然写行将每个条目写到excel csv文件中的单独行中,而不是同一行。 Do you know how to fix this? 你知道如何解决这个问题吗?

writerow writes a single row. writerow写一行。 If you want to write multiple rows and use this function then you have to call it separately for each row: 如果要编写多行并使用此函数,则必须为每一行分别调用它:

import csv
testfile=['free', 'great', 'congratulations', 'great', 'kind', 'freedom']
with open("pos_words_pre.csv",'w') as resultFile_pos_pre:
    wr_pos_pre = csv.writer(resultFile_pos_pre)
    for row in testfile:
        wr_pos_pre.writerow([row])

Alternatively you can write many rows at once: 或者,您可以一次写很多行:

with open("pos_words_pre.csv",'w') as resultFile_pos_pre:
    wr_pos_pre = csv.writer(resultFile_pos_pre)
    wr_pos_pre.writerows(([row] for row in testfile))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM