[Tutor] Reading information from a text file into a list of lists (WinXP/py2.6.2)

Katt the_only_katala at verizon.net
Sun Oct 25 23:53:54 CET 2009


Hello all,

Currently I am working on a program that reads text from a text file.  I 
would like it to place the information int a list and inside the information 
would have sublists of information.

The text file looks like this:

"Old Test","2009_10_20"
"Current Test","2009_10_25"
"Future Test","2009_11_01"

I am trying to get the list of lists to look like the following after the 
information is read from the text file:

important_dates = [["Old Test","2009_10_20"],["Current 
Test",2009_10_25"],["Future Test","2009_11_01"]]

What I currently have is:

def read_important_dates():
    print "\nReading text file into program: important.txt"
    text_file = open("important.txt", "r")
    dates = text_file.readlines()
    text_file.close()
    print dates
#
read_important_dates()

When it gets to print dates I see the following:

[ ' "Old Test","2009_10_20"\n',  ' "Current Test",2009_10_25"\n',  ' "Future 
Test","2009_11_01" ' ]

Does it look this way because I am using the "print"?  Or do I still need to 
add the inner [ ] and strip out the \n and '?
If I add brackets to the text file I am reading from my output looks like 
this:

['["Old Test","2009_10_20"]\n', '["Current Test",2009_10_25"]\n', '["Future 
Test","2009_11_01"]']

The program in which I am reading the information into reads a list of lists 
in which I am trying to simulate when reading from the text file mentioned 
above.

Which acomplishes the in list's brackets, but still leaves the \n and the ' 
characters.

I have tried line.strip() to remove the \n and ' characters, but get the 
following error:

Reading text file into program: important.txt
Traceback (most recent call last):
    File "fileio.py", line 9, in <module>
        read_important_dates()
    File "fileio.py", line 6, in read_important_dates
        line.strip()
NameError: global name 'line' is not defined

If I try the following to split dates into another list called 
important_dates I receive a different error:

---------code----------
def read_important_dates():
    print "\nReading text file into program: reminders.txt"
    text_file = open("important", "r")
    dates = text_file.readlines()
    text_file.close()
    important_dates = dates.split()
    print dates
    print important_dates
#
read_important_dates()
-------------------------
--------error-----------
Reading text file into program: important.txt
Traceback (most recent call last):
    File "fileio.py", line 10, in <module>
        read_important_dates()
    File "fileio.py", line 6, in read_important_dates
        important_dates = dates.split()
NameError: 'list' object has no attribute 'split'
--------------------------

All help is appreciated,

Thanks in advance,

Katt



More information about the Tutor mailing list