如何读取和写入表/矩阵文件与Python? [英] How to read and write a table / matrix to file with python?

查看:160
本文介绍了如何读取和写入表/矩阵文件与Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个程序来获取数据,并把它放在一个2×10的表格中,只是一个文本文件中的数字。然后程序需要在以后的迭代中检索这个信息。但我不知道如何做到这一点。我一直在查看numpty命令,常规文件命令,以及尝试制作表格的方法。但我似乎无法得到任何这个工作。



下面是我想要创建的表格的示例:

  0 1 1 1 0 9 6 5 
5 2 7 2 1 1 1 0

然后我会检索这些值。什么是这样做的好方法?

解决方案

为什么不使用 csv 模块? b
$ b

  table = [[1,2,3],[4,5,6]] 

导入csv

#用open('test_file.csv','w')写成
作为csvfile:
writer = csv.writer(csvfile)
[writer.writerow r)for r in table]

#以open('test_file.csv','r')读取
作为csvfile:
reader = csv.reader(csvfile)
table = [[int(e)for e in r] for r in reader]

这种方法的好处是可以让其他程序(如Excel)读取文件。

如果你真的需要它的空间或制表符分隔,只需添加 delimiter =\ t添加到您的读写器构建中。


I'm trying to create a program that takes data and puts it in a 2 by 10 table of just numbers in a text file. Then the program needs to retrieve this information in later iterations. But I have no idea how to do this. I've been looking at numpty commands, regular file commands, and ways to try and make a table. But I can't seem to get any of this to work.

Here is an example of the table I am trying to make:

0    1    1    1    0    9    6    5
5    2    7    2    1    1    1    0

Then I would retrieve these values. What is a good way to do this?

解决方案

Why not use the csv module?

table = [[1,2,3],[4,5,6]]

import csv

# write it
with open('test_file.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    [writer.writerow(r) for r in table]

# read it
with open('test_file.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    table = [[int(e) for e in r] for r in reader]

This approach has the added benefit of making files that are readable by other programs, like Excel.

Heck, if you really need it space or tab-delimited, just add delimiter="\t" to your reader and writer construction.

这篇关于如何读取和写入表/矩阵文件与Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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