Reading from a file and converting it into a list of lines: code not working
skip at pobox.com
skip at pobox.com
Tue Jun 6 09:04:35 EDT 2006
Girish> I have a text file in the following format:
Girish> 1,'a',2,'b'
Girish> 3,'a',5,'c'
Girish> 3,'a',6,'c'
Girish> 3,'a',7,'b'
Girish> 8,'a',7,'b'
Girish> .
Girish> .
Girish> .
Girish> Now i need to generate 2 things by reading the file:
Girish> 1) A dictionary with the numbers as keys and the letters as values.
Girish> e.g the above would give me a dictionary like
Girish> {1:'a', 2:'b', 3:'a', 5:'c', 6:'c' ........}
Girish> 2) A list containing pairs of numbers from each line.
Girish> The above formmat would give me the list as
Girish> [[1,2],[3,5],[3,6][3,7][8,7]......]
Running this:
open("some.text.file", "w").write("""\
1,'a',2,'b'
3,'a',5,'c'
3,'a',6,'c'
3,'a',7,'b'
8,'a',7,'b'
""")
import csv
class dialect(csv.excel):
quotechar = "'"
reader = csv.reader(open("some.text.file", "rb"), dialect=dialect)
mydict = {}
mylist = []
for row in reader:
numbers = [int(n) for n in row[::2]]
letters = row[1::2]
mydict.update(dict(zip(numbers, letters)))
mylist.append(numbers)
print mydict
print mylist
import os
os.unlink("some.text.file")
displays this:
{1: 'a', 2: 'b', 3: 'a', 5: 'c', 6: 'c', 7: 'b', 8: 'a'}
[[1, 2], [3, 5], [3, 6], [3, 7], [8, 7]]
That seems to be approximately what you're looking for.
Skip
More information about the Python-list
mailing list