python怎么写csv文件,在Python中写入csv文件

The code I have

i = 0

while i < len(newsymbolslist):

time = 102030

data = 895.233

array = [time], [data]

with open('StockPrice.csv', 'wb') as file:

file_writer = csv.writer(file)

file_writer.writerow(array)

file.close()

i += 1

I'm fairly new to Python so I'm not 100% sure why the previous code only enters data into the top row. My guess is that because I'm opening and the file each iteration it doesn't know that its not suppose to override. I know how to fix it in theory (if that is the problem). I'm just having trouble with syntax.

My guess: use the iterations (var i) to count how many rows down the file should write.

解决方案with open('StockPrice.csv', 'wb') as f:

file_writer = csv.writer(f)

for s in newsymbolslist:

time = 102030

data = 895.233

array = [time], [data]

file_writer.writerow(array)

Your first guess is correct: Every time you open the file in 'wb' mode, the file is effectively deleted (if it existed) and a new empty file is created. So only the contents written during the last iteration through the while-loop affects the contents of the file.

The solution is to open the file once (before the loop begins).

Note that opening the file with the with-statement guarantees that the file will be closed when Python leaves the with-block. So there is no need to call f.close() yourself.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值