aloha
aloha

Reputation: 4784

Save a list in python

I am trying to export my output to a list. Here is my code:

import csv
import numpy as np

row_list = np.arange(0,5)
for row in row_list:
    a = row + 3
    b = row + 4
    c = row + 5


    result = [a, b, c]
    csvfile = "/home/Desktop/test"

    with open(csvfile, "w") as output:
        writer = csv.writer(output, lineterminator='\t')
        for val in result:
            writer.writerow([val])

I run the code, a test file is created on my desktop (which is exactly what I want) but the data in the file is wrong. The output is: 7 8 9

But this is not what I want. The script is running through the loop but it's only exporting the last line. Any ideas on how to get it to export the data in the file in the following manner:

3 4 5
4 5 6
5 6 7
6 7 8
7 8 9

Thanks!

EDIT: What if I want to give this script to my professor. The directory /home/paula/Desktop/test does not exist on her laptop. I tried to write csvfile = "~/Desktop/test" but it gave me an error. Any idea?

Note: I am using ubuntu 12.04.

Upvotes: 1

Views: 1690

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122106

You open() the file again each time through the loop, using 'w' ((over)write) as the file mode rather than 'a' (append). See the Python docs for more on reading and writing files.

Alternatively, open the file outside the loop:

csvfile = "/home/paula/Desktop/test"
with open(csvfile, 'w') as f:
    writer = csv.writer(output, lineterminator='\t')
    for row in rowlist:
        # do the output here

Upvotes: 0

user2357112
user2357112

Reputation: 281594

When you open a file in the w mode, it erases any existing contents. Even if it didn't, you're not writing a newline character at the end of your lines.

Open the file once, and use a more sensible concept of "row" - one that corresponds to actual rows of your data:

with open(csvfile, "w") as output:
    writer = csv.writer(output, delimiter='\t')

    for row_num in row_list:
        a = row_num + 3
        b = row_num + 4
        c = row_num + 5

        row = [a, b, c]
        writer.writerow(row)

Upvotes: 1

MattDMo
MattDMo

Reputation: 102902

Each time you open csvfile in w mode you are truncating it down to 0 bytes. Instead, open the new file in a mode, which will append data to it.

Upvotes: 0

Related Questions