[英]Writing to csv file in Python
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. 我是Python的新手,所以我不确定100%为什么前面的代码只将数据输入到第一行。 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. 我的猜测:使用迭代(var i)计算文件应向下写入多少行。
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. 您的第一个猜测是正确的:每次以
'wb'
模式打开文件时,该文件都会被有效删除(如果存在)并创建一个新的空文件。 So only the contents written during the last iteration through the while-loop
affects the contents of the file. 因此,只有在上一次迭代中通过
while-loop
写入的内容会影响文件的内容。
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
. 请注意,使用with语句打开文件可确保Python离开
with-block
时将关闭文件。 So there is no need to call f.close()
yourself. 因此,您无需自己调用
f.close()
。
From the documentation : 从文档中 :
The most commonly-used values of mode are
'r'
for reading,'w'
for writing ( truncating the file if it already exists ), and'a'
for appending (...)模式最常用的值是
'r'
表示读取,'w'
表示写入( 如果文件已经存在 , 则将其截断 ),以及'a'
表示附加(...)
If you want to write to the end of an existing file, open it in append mode, with 'a'
. 如果要写入现有文件的末尾,请在附加模式下使用
'a'
打开它。 (Though in this case, yes, restructuring your loop is the better answer.) (尽管在这种情况下,是的,重组循环是更好的答案。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.