简体   繁体   English

将变量中的存储数据写入CSV文件时出现问题

[英]getting issue while writing stored data in a variable to csv file

Example: I'm writing this data to a csv file: 示例:我正在将此数据写入一个csv文件:

data = 'Fiber är beställd till adressen. Tjänsterna kan du beställa när installationen är färdig.'

I've write this code to do this: 我已经编写了以下代码来做到这一点:

with open('test.csv','a',encoding='utf-8',newline='') as fp:
    writer = csv.writer(fp, delimiter=',')
    writer.writerow(data)

When this code runs it gives the output as follows: Here's the image 运行此代码时,其输出如下: 这是图像

This program is writing each letter separately but i want to write the whole text variable into single cell and then move to the next row for writing next variable's data into the new cell. 这个程序是分别写每个字母,但我想将整个文本变量写到单个单元格中,然后移到下一行以将下一个变量的数据写到新单元格中。 thanks 谢谢

casv.writerow() accepts an iterable as the row. casv.writerow()接受可迭代的行。 In this case it interprets the string as an iterable and its characters as respective items for each field. 在这种情况下,它将字符串解释为可迭代,并将其字符解释为每个字段的相应项目。 If you want to write the string in one field you can put it in an iterable like tuple. 如果要将字符串写在一个字段中,则可以将其放在类似tuple的可迭代区域中。

writer.writerow((data,))

Or you can split the data with the intended delimiter: 或者,您可以使用预期的分隔符分割数据:

writer.writerow(data.split(','))

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

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