Python从文件读取到多个列表 [英] Python reading from file into multiple lists

查看:416
本文介绍了Python从文件读取到多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为有人可以指出我正确的方向吗?

I don't suppose someone could point me in the right direction?

我有点想知道如何最好地将值从文本文件中提取出来,然后将其分解,然后将它们放回与相应值相同位置的列表中.

I'm a bit wondering how best to pull values out of a text file then break them up and put them back into lists at the same place as their corresponding values.

对不起,如果不清楚,也许这样会使情况更清楚.这是输出文件的代码:

I'm sorry If this isn't clear, maybe this will make it clearer. This is the code that outputs the file:

#while loop       
with open('values', 'a') as o:
             o.write("{}, {}, {}, {}, {}, {}, {}\n".format(FirstName[currentRow],Surname[currentRow], AnotherValue[currentRow], numberA, numberB))
currentRow+1

我想做相反的事情,并采用如上所述格式设置的值,然后将它们放回到同一位置的列表中.像这样:

I would like to do the opposite and take the values, formatted as above and put them back into lists at the same place. Something like:

#while loop
with open('values', 'r') as o:
             o.read("{}, {}, {}, {}, {}, {}, {}\n".format(FirstName[currentRow],Surname[currentRow], AnotherValue[currentRow], numberA, numberB))
currentRow +1

谢谢

推荐答案

如果允许您确定文件格式,则保存和加载为json格式可能会有用.

If you are allow to decide file format, saving and loading as json format may be useful.

import json

#test data
FirstName    = range(5)
Surname      = range(5,11)
AnotherValue = range(11,16)
numberAvec   = range(16,21)
numberBvec   = range(21,26)

#save
all = [FirstName,Surname,AnotherValue,numberAvec,numberBvec]
with open("values.txt","w") as fp:
    json.dump(all,fp)

#load
with open("values.txt","r") as fp:
    FirstName,Surname,AnotherValue,numberAvec,numberBvec = json.load(fp)

values.txt:

values.txt:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]

这篇关于Python从文件读取到多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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