File I/O

half.italian at gmail.com half.italian at gmail.com
Wed May 9 17:35:25 EDT 2007


On May 9, 2:13 pm, HMS Surprise <j... at datavoiceint.com> wrote:
> If one has a list of lists such as
>
> lst = [['a','1'],['b','2']]
>
> is there a standard python idiom for writing and reading the pairs to/
> from a file?
>
> Thanks,
>
> jh

These work.  Assuming you can choose the format.  Or you could pickle
the list.

write
~~~~
lst = [['a','1'],['b','2']]

file = open("file", 'w')
[file.write(item[0] + "\t" + item[1] + "\n") for item in lst]
file.close()

read
~~~~
lst = []
file = open("file", 'r')
[lst.append(list(line.split())) for line in file]
file.close()

print lst

~Sean




More information about the Python-list mailing list