在Python中写入csv文件
代码我有
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
我对Python很新,所以我不是100%肯定以前的代码只输入数据到顶行。我的猜测是,因为我打开和文件每次迭代它不知道,它不假设重写。我知道如何解决它在理论(如果这是问题)。我只是麻烦了语法。
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.
我的猜测:使用迭代(var i)来计算文件应该写多少行。
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)
你的第一个猜测是正确的:每次你打开'wb'
模式下,文件将被有效删除(如果存在),并创建一个新的空文件。因此,只有在最后一次迭代期间通过 while-loop
写入的内容会影响文件的内容。
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).
注意,打开文件时需要使用 with-statement 保证当Python离开 with-block
时,该文件将被关闭。因此,不需要自己调用 f.close()
。
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.