在python中保存列表 [英] Save a list in python

查看:380
本文介绍了在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])

运行代码,在桌面上创建了一个测试文件(这正是我想要的),但是文件中的数据错误. 输出为: 7 8 9

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

谢谢!

如果我想将此脚本提供给我的教授,该怎么办.她的笔记本电脑上不存在目录/home/paula/Desktop/test.我试图写csvfile = "~/Desktop/test",但它给了我一个错误.任何的想法?

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?

注意:我正在使用ubuntu 12.04.

Note: I am using ubuntu 12.04.

推荐答案

w模式下打开文件时,它将删除所有现有内容.即使不是,也不会在行尾写换行符.

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)

这篇关于在python中保存列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆