How can I use python for file processing

Ricardo Aráoz ricaraoz at
Sun Aug 26 14:09:58 CEST 2007

Marc 'BlackJack' Rintsch wrote:
> On Sun, 26 Aug 2007 06:05:11 +0000, yinglcs at wrote:
>> I am trying to use python for file processing.
>> Suppose I have a file like this:
>> I want to build a Hashmap between the line "begin_QOS_statistics" and
>> "end_QOS_statistics"
>> and for each line I want to put the first text as the key of the hash
>> table and the second text as the value.
> Work through the tutorial, experiment a little in the interactive
> interpreter and then just do it.  You need to `open()` the file, iterate
> over its lines in a ``for``-loop, decide to when it is time to start
> processing lines, and then `str.split()` the lines and put them into a
> `dict()`.  This is a neat little project to start learning the language.
> Ciao,
> 	Marc 'BlackJack' Rintsch

Just posted this on Python Tutor, might give you a start :

nameFile = open(r'/path/to/file.txt', 'rU')
phonebook = {}

for line in nameFile :
    phonebook.setdefault(line[0].upper(), []).append(line.strip('\n'))

for item, names in phonebook.iteritems() :

print phonebook


More information about the Python-list mailing list