Reading files into a 2D list.
Oyvind Ostlund
Oyvind.Ostlund at cern.ch
Wed May 11 06:35:34 EDT 2005
-----Original Message-----
From: python-list-bounces+oyvind.ostlund=cern.ch at python.org [mailto:python-list-bounces+oyvind.ostlund=cern.ch at python.org] On Behalf Of Klaus Alexander Seistrup
Sent: Wednesday, May 11, 2005 12:14 PM
To: python-list at python.org
Subject: Re: Reading files into a 2D list.
Øyvind Østlund wrote:
> I have a list of about 20 files that I want to read line by line into
> a 2D list. So the first dimension will be each file, and the second
> every line in that file.
>
> I tried to do something like this:
>
> files_and_lines = [][]
> filenumber = 0
>
> for files in file_names:
> try:
> lexi_file = open(str(sys.path[0]) + "/lexi/" + files, "r")
> files_and_lines[filenumber] = lexi_file.readlines()
> filenumber = filenumber + 1
>
> except(IOError):
> print "Something went wrong trying to read the file:"
> print "'" + str(sys.path[0]) + files + "'"
I'm not sure I understand you. Do you wish to end up with an array like this:
#v+
[fileName0][fileLines0]
[fileName1][fileLines1]
...
[fileNameN][fileLinesN]
#v-
In that case try something like:
#v+
>>> files_and_lines = []
>>> for name in file_names:
>>> files_and_lines.append([name, open(name, 'r').readlines()])
>>> print 'Read %d files' % (len(files_and_lines),)
#v-
Add proper error checking.
At least, I think the [].append() method is what you're looking for.
Cheers,
--
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/
--
http://mail.python.org/mailman/listinfo/python-list
Thanks for the reply. But I might have been a bit clearer.
What I want to do is to be able to write:
files_and_lines[5][5]
And then I am accessing the 6th line in the 6th file, so I can print that line if I want, or do what ever I want with it. So if I did this:
If files_and_lines[1][1] == files_and_lines[1][100]:
Then I would check if those two lines had the same content. I tried your solution, and if I didn't do anything else wrong, I think you missunderstood me a bit, because if I try print files_and_lines[1][1] now, it prints whole lot more then just one line from file 2.
Thanks
ØØ
More information about the Python-list
mailing list