eval
is something to be avoided and, fortunately, it is almost never needed. In this case, open(recType+".raw",'w')
creates a file handle. You just need to associate it with recType. This is what dictionaries are for.
In the code below, openFiles
is a dictionary. Every time that we encounter a new recType
, we open a file for it and save its filehandle in openFiles
under the key recType
. Whenever we want to write to that file again, we just ask the dictionary for the file handle. Thus:
openFiles = {}
for line in fileinput.input(src):
parts = line.split('|')
recType = parts[7]
if not recType in openFiles:
openFiles[recType] = open('f_' + recType, 'w')
openFiles[recType].write(line)
# ....