Skip to content Skip to sidebar Skip to footer

Python Reading From File Into Multiple Lists

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

Solution 1:

I think the best corresponding way to do it is calling split on the text read in:

FirstName[currentRow],Surname[currentRow], AnotherValue[currentRow], numberA, numberB = o.read().strip().split(", ")

There is no real equivalent of formatted input, like scanf in C.

Solution 2:

You should be able to do something like the following:

first_names = []
surnames = []
another_values = []
number_as = []
number_bs = []

for line in open('values', 'r'):
    fn, sn, av, na, nb = line.strip().split(',')
    first_names.append(fn)
    surnames.append(sn)
    another_values.append(av)
    number_as.append(float(na))
    number_bs.append(float(nb))

The for line in open() part iterates over each line in the file and the fn, sn, av, na, nb = line.strip().split(',') bit strips the newline \n off the end of each line and splits it on the commas.

In practice though I would probably use the CSV Module or something like Pandas which handle edge cases better. For example the above approach will break if a name or some other value has a comma in it!

Solution 3:

withopen('values.txt', 'r') as f:
    first_names, last_names, another_values, a_values, b_values = \
    (list(tt) for tt inzip(*[l.rstrip().split(',') for l in f]))

Unless you need update, list conversion list(tt) for tt in is also unnecessary.

May use izip from itertools instead of zip.

Solution 4:

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)

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

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

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]]

Post a Comment for "Python Reading From File Into Multiple Lists"