使用for循环写入csv [英] Writing to csv with for loops

查看:320
本文介绍了使用for循环写入csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为list_people中的每个项目写一个新的名字和年龄。如果列表中有3个人,我的CSV应该有3行2列,如下所示:

  Joann 15 
Maria 13
Peter 19

我的CSV为我提供了1行6列如下:

  Joann 15 Maria 13 Peter 19 

这是我使用的代码。

  row_lines = [] 

为list_people中的我:

info = inspect.getmembers(i)

name = info [1]
row_lines.append(name)
age = info [2]
row_lines.append(age )

with open('test.csv','w')as csvFile:
writer = csv.writer(csvFile,delimiter =',',quotechar ='|',quoting = csv.QUOTE_MINIMAL,lineterminator ='\\\
')
writer.writerow(row_lines)

我需要改变什么,以便为我的循环的每个迭代写入一个新行(对于list_people中的每个人)?

解决方案

打开你的 csv 文件一次,每次迭代写一行,不需要太多变量:
$ b作为csvFile:
writer = csv.writer(csvFile,delimiter =',',quotechar ='$',$ b

  '|',quoting = csv.QUOTE_MINIMAL,lineterminator ='\\\
')

for i in list_people:
info = inspect.getmembers(i)
writer.writerow(info [1:3])

或完全用编写者替换循环,使用生成器理解甚至更快:

  writer.writerows(inspect.getmembers(i)[1:3] for list_people)


I am trying to write a new row for each item in list_people with the name and age of the person. If there are 3 people in the list, my CSV should have 3 rows and 2 columns as shown below:

Joann  15
Maria  13
Peter  19

My CSV gives me 1 row and 6 columns as shown below:

Joann 15 Maria 13 Peter 19

Here is the code I am using.

row_lines=[] 

for i in list_people:

    info = inspect.getmembers(i)

    name = info[1]
    row_lines.append(name)
    age = info[2]
    row_lines.append(age)

with open('test.csv', 'w') as csvFile:
    writer=csv.writer(csvFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(row_lines)

What do I need to change so that it writes to a new row for each iteration of my loop (for each person in the list_people)?

解决方案

open your csv file once, and write one line per iteration, and no need for so many variables:

with open('test'.csv, 'w') as csvFile:
   writer=csv.writer(csvFile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')

   for i in list_people:
       info = inspect.getmembers(i)
       writer.writerow(info[1:3])

or completely replace the for loop by writerows using a generator comprehension, that will be even faster:

writer.writerows(inspect.getmembers(i)[1:3] for i in list_people)

这篇关于使用for循环写入csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆