[Tutor] Lists in a file

spir denis.spir at free.fr
Sun Apr 26 21:22:52 CEST 2009


Le Sun, 26 Apr 2009 18:03:41 +0000 (GMT),
David Holland <davholla2002 at yahoo.co.uk> s'exprima ainsi:

> Hi,
> 
> I am trying to create a program where I open a file full of lists and
> process them. However when the program does not recognize the lists as
> lists. Here is the relevant code :-
> def open_filedef():
>     text_file =open ("voteinp.txt","r")
>     lines = text_file.readlines()
>     
>     
>     for line in lines:
>         print line
>         print line[0]
>           
>     text_file.close()
> 
> And an example of the type of text :-
> 
> ['a','b','c']
> ['e','d','f']
> 
> Any ideas?
 
You're making a confusion between text items and what could be called "running program items". And also you're assuming that python reads your mind -- a feature not yet implemented but in project for py4000.
More seriously, a list (or any "running program item") is something that is produced in memory when python runs your code, like when it runs
   l = [1,2,3]
after having parsed it.

What you're giving it now is *text*. Precisely text read from a file. So it regards as text. It could hold "I am trying to create a program where...". Right? Python has no way to guess that *you* consider this text as valid python code. You must tell it.
Also, you do not ask python to run this. So why should it do so? Right?

If you give python a text, it regards it as text (string):
>>> t = "[1,2,3] ; [7,8,9]"
>>> t
'[1,2,3] ; [7,8,9]'
>>> type(t)
<type 'str'>

A text is a sequence of characters, so that if you split it into a list, you get characters; if you ask for the zerost char, you get it:
>>> list(t)
['[', '1', ',', '2', ',', '3', ']', ' ', ';', ' ', '[', '7', ',', '8', ',', '9', ']']
>>> t[0]
'['

If you want python to consider the text as if it were code, you must tell it so:
>>> listtext1 = t[0:7]
>>> listtext1
'[1,2,3]'
>>> list1 = eval(listtext1)
>>> list1
[1, 2, 3]
>>> list1[1]
2

Now, as you see, I have a list object called list1. But this is considered bad practice for numerous good reasons.
Actually, what you were doing is asking python to read a file that you consider as a snippet of program. So why don't you write it directly in the same file? Or for organisation purpose you want an external module to import?

Denis
------
la vita e estrany


More information about the Tutor mailing list