Writing to csv file in Python

The code that 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 am new to Python, so I'm not 100% sure why the previous code only enters data on the top line. I assume that due to the fact that I open the file and each iteration, it does not know that it should not be redefined. I know how to fix this in theory (if this is a problem). I just have problems with the syntax.

My guess: use iterations (var i) to calculate how many lines should be written to the file.

+1
source share
2 answers
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, .

, ( ).

, with-statement , , Python with-block. f.close() .

+4

:

'r' , 'w' ( , ), 'a' (... )

, , 'a'. ( , - .)

+2

Source: https://habr.com/ru/post/1541819/


All Articles