Reading files into a 2D list.

Oyvind Ostlund Oyvind.Ostlund at cern.ch
Wed May 11 05:39:20 EDT 2005


I am not sure what the right syntax is here. So please help me out (started 2 days ago).

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 + "'"



But that was not very sucksessfully. I am not even sure on how to define an empty 2D list. Thanks for all help.

ØØ



More information about the Python-list mailing list