1

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.

chenaren
  • 2,090
  • 1
  • 19
  • 24
user1861156
  • 169
  • 1
  • 2
  • 14
  • your guess is correct, it's better to just open the file first (before the loop begins and then do the rest of activity with that one file handler) next do the file.close(); once the loop is finished (as the last step) – Ahmed Masud May 25 '13 at 01:10
  • Why would you open and close the file every iteration? Also, you are writing to it, which starts from the beginning. If you wanted to do it how you are doing it (which you shouldn't) use the buffer mode 'a' (append). – Rushy Panchal May 25 '13 at 01:12

2 Answers2

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

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

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

Cairnarvon
  • 25,981
  • 9
  • 51
  • 65