[Tutor] Importing file data into Python arrays
Kalle Svensson
kalle@lysator.liu.se
Mon, 27 May 2002 23:31:00 +0200
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
[Alistair McGowan]
> import array
For the examples you have shown, there is no need to import array.
You are using lists, a basic datatype in Python.
The array module, documented at
http://python.org/doc/current/lib/module-array.html might be of
interest to you anyway, as well as the numeric python extensions at
http://www.pfdubois.com/numpy/ .
> However, when I try to read in data from a file as shown below, I
> end up with the lines, which I can't manipulate.
You will have to manipulate the lines a bit to go from strings to
integers. How to do this depends on what you want. If you want a
nested list like
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
something like this should work:
arr = []
inp = open ("dat.txt","r")
#read line into array
for line in inp.readlines():
# add a new sublist
arr.append([])
# loop over the elemets, split by whitespace
for i in line.split():
# convert to integer and append to the last
# element of the list
arr[-1].append(int(i))
To get a flat list like
[1, 2, 3, 4, 5, 6, 7, 8, 9]
this might do:
arr = []
inp = open ("dat.txt","r")
#read line into array
for line in inp.readlines():
# loop over the elemets, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
Hope this helps.
Peace,
Kalle
- --
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>
iD8DBQE88qWMdNeA1787sd0RAplBAJ4wvzXzWLaS2n46kIZi8FSe3nRVbgCgu3lF
tb96o7nErPGBzx6dROjQj0M=
=7/cM
-----END PGP SIGNATURE-----