user1861156
user1861156

Reputation: 169

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. 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.

Upvotes: 1

Views: 648

Answers (2)

unutbu
unutbu

Reputation: 880877

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.

Upvotes: 4

Cairnarvon
Cairnarvon

Reputation: 27832

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 (...)

If you want to write to the end of an existing file, open it in append mode, with 'a'. (Though in this case, yes, restructuring your loop is the better answer.)

Upvotes: 2

Related Questions