Save a list in python

安稳与你 提交于 2019-12-13 00:56:58

问题


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.


回答1:


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)



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/21244672/save-a-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!